using UnityEngine;
public class Movement
{
public Vector2 targetPos; // 目标位置
public Vector2 selfPos; // 当前位置信息
public float maxSpeed; // 最大速度
// 手动实现的归一化函数
public static Vector2 NormalizeSafe(Vector2 vector)
{
float length = vector.magnitude; // 使用magnitude计算向量长度
if (length == 0f)
{
return Vector2.zero; // 返回零向量,避免除零错误
}
else
{
return vector / length; // 归一化
}
}
// 计算优先速度
public Vector2 CalculatePrefVelocity()
{
// 计算位移向量
Vector2 displacement = targetPos - selfPos;
// 归一化位移向量
Vector2 direction = NormalizeSafe(displacement);
// 计算优先速度
Vector2 prefVelocity = direction * maxSpeed;
return prefVelocity;
}
}
假设你在游戏中有一个角色,目标是让这个角色朝目标位置移动,同时确保它不会超过最大速度 maxSpeed
。这个类 Movement
中的 CalculatePrefVelocity
方法可以根据目标位置和当前位置信息来计算角色的优先速度。