Files
zeling_v2/Assets/_Game/Scripts/Combat/HomingProjectile.cs

41 lines
1.2 KiB
C#

using UnityEngine;
namespace BaseGames.Combat
{
/// <summary>
/// 追踪抛射物。初始以 Direction 发射后,每帧向目标转向,
/// 转向力由 <see cref="ProjectileConfigSO.HomingStrength"/> 控制。
/// </summary>
public class HomingProjectile : Projectile
{
private Transform _target;
/// <summary>注入追踪目标(由 ProjectileManager 在生成时调用)。</summary>
public void SetTarget(Transform t) => _target = t;
protected override void OnInitialized()
{
_rb.velocity = Direction * _config.Speed;
}
protected override void Update()
{
base.Update();
if (_target == null || _config == null) return;
Vector2 toTarget = ((Vector2)_target.position - _rb.position).normalized;
_rb.velocity += toTarget * (_config.HomingStrength * Time.deltaTime);
float maxSpeed = _config.Speed * 1.5f;
if (_rb.velocity.sqrMagnitude > maxSpeed * maxSpeed)
_rb.velocity = _rb.velocity.normalized * maxSpeed;
}
protected override void OnDisable()
{
base.OnDisable();
_target = null;
}
}
}