思想是:宠物离的越远,速度越快,越近,速度越慢。可以做做距离插值
public float SpeedLerp = 1f;
public float SpeedMin = 0.5f; // 防止距离近的时候移动过慢
// -------
void Update(){
// 触发条件
mPetToPlayerDistance = Vector3.Distance(
mCityPlayerCtl.Position,
mModelObj.transform.position);
if (mPetToPlayerDistance < mSeekDistance)
{
mState = CityPetState.Idle;
}
else
{
mState = CityPetState.Seek;
}
switch (mState)
{
case CityPetState.Idle:
Idle();
break;
case CityPetState.Seek:
Seek();
break;
default:
break;
}
}
void Seek()
{
// 计算朝向
Vector3 vector = mCityPlayerCtl.transform.position - mModelObj.transform.position;
vector = Vector3.ProjectOnPlane(vector, Vector3.up);
var direct = Vector3.Normalize(vector);
#if UNITY_EDITOR
Debug.DrawRay(mModelObj.transform.position, direct);
#endif
// 计算"速度"
var PetPosition = mModelObj.transform.position;
var mMoveDestPos = mCityPlayerCtl.Position;
mMoveDestPos += new Vector3(0, 1.5f, 0);
float moveDelta = Mathf.Lerp(0,
mPetToPlayerDistance - mSeekDistance,
SpeedLerp * CommonData.DeltaTime);
float minDelta = SpeedMin * CommonData.DeltaTime;
moveDelta = Mathf.Max(moveDelta, minDelta);
PetPosition = Vector3.MoveTowards(PetPosition, mMoveDestPos, moveDelta);
mModelObj.transform.position = PetPosition;
mModelObj.transform.forward =
Vector3.Slerp(mModelObj.transform.forward, direct, CommonData.DeltaTime * 5);
}
private void Idle()
{
mLogicAnimator.SetInteger("MoveStage", 0);
IsMoveAction = true;
}