#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
跟随脚本 - 让对象跟随指定的目标对象
"""

from core.script_system import ScriptBase
from panda3d.core import Vec3

class FollowerScript(ScriptBase):
    """跟随脚本类"""
    
    def __init__(self):
        super().__init__()
        self.target = None             # 跟随目标
        self.follow_speed = 5.0        # 跟随速度
        self.follow_distance = 2.0     # 跟随距离
        self.is_following = True       # 是否正在跟随
    
    def start(self):
        """脚本开始时调用"""
        self.log("跟随脚本启动！")
        self.log(f"跟随参数: 速度={self.follow_speed}, 距离={self.follow_distance}")
    
    def update(self, dt):
        """每帧更新"""
        if not self.is_following or self.target is None:
            return
        
        target_pos = self.target.getPos()
        current_pos = self.gameObject.getPos()
        
        # 计算目标方向
        direction = target_pos - current_pos
        distance = direction.length()
        
        # 如果距离大于跟随距离，则移动
        if distance > self.follow_distance:
            if distance > 0:
                direction.normalize()
            
            # 计算目标位置（保持跟随距离）
            target_follow_pos = target_pos - direction * self.follow_distance
            
            # 平滑移动到目标位置
            move_direction = target_follow_pos - current_pos
            move_distance = move_direction.length()
            
            if move_distance > 0:
                move_direction.normalize()
                move_amount = min(self.follow_speed * dt, move_distance)
                new_pos = current_pos + move_direction * move_amount
                self.gameObject.setPos(new_pos)
        
        # 朝向目标
        self.gameObject.lookAt(target_pos)
    
    def set_target(self, target):
        """设置跟随目标"""
        self.target = target
        if target:
            self.log(f"设置跟随目标: {target.getName()}")
        else:
            self.log("清除跟随目标")
    
    def on_destroy(self):
        """脚本销毁时调用"""
        self.log("跟随脚本停止") 