说明
- 在xoz平面内,物体在指定时间内从A点移动至B点。
- B点可以是一个实时运动的点。
- 物体的Y坐标根据实际配置的曲线得到。
这里的Y(xoz平面)实际也可以是X(yoz平面)或Z(xoy平面)。
使用方式
调用FanCurveMoveObj.Move(),传入移动所需的参数。
实现
FanCurveMoveObj.cs
其中包含
- 2个类
FanCurveMoveObj:移动物体
FanCurveMoveModel:移动所需参数 - 1个枚举
FanActualYAxis:移动定义中的Y对应的实际的坐标轴
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FanCurveMoveObj : MonoBehaviour
{
public void Init()
{ }
public void Destroy()
{
DestroyMove();
}
private IEnumerator _moveCoroutine;
public void Move(FanCurveMoveModel model)
{
DestroyMove();
_moveCoroutine = MoveCoroutine(model);
Utils.StartCoroutine(_moveCoroutine);
IEnumerator MoveCoroutine(FanCurveMoveModel model)
{
SetPos(AdjustPos(model.BeginPos, model.EndPos, model.YCurve, 0));
float timer = 0f;
while (timer < model.MoveDurationSeconds)
{
SetPos(AdjustPos(model.BeginPos, model.EndPos, model.YCurve, timer / model.MoveDurationSeconds));
timer += Time.deltaTime;
yield return null;
}
SetPos(AdjustPos(model.BeginPos, model.EndPos, model.YCurve, 1));
}
void SetPos(Vector3 pos)
{
transform.position = pos;
}
Vector3 AdjustPos(Vector3 beginPos, Vector3 endPos, AnimationCurve curve, float ratio)
{
ratio = Mathf.Clamp01(ratio);
var pos = Vector3.Lerp(beginPos, endPos, ratio);
float actualY = model.BaseY + model.YFactor * model.YCurve.Evaluate(ratio);
switch (model.YAxis)
{
case FanActualYAxis.X:
pos.x = actualY;
break;
case FanActualYAxis.Y:
pos.y = actualY;
break;
case FanActualYAxis.Z:
pos.z = actualY;
break;
default:
break;
}
return pos;
}
}
private void DestroyMove()
{
Utils.DestroyCoroutine(ref _moveCoroutine);
}
}
[System.Serializable]
public class FanCurveMoveModel
{
public Vector3 BeginPos;
public Transform EndTrans;
public Vector3 EndPos => EndTrans.position;
public float MoveDurationSeconds;
public FanActualYAxis YAxis;
public float BaseY;
public float YFactor;
public AnimationCurve YCurve;
}
public enum FanActualYAxis
{
None,
X,
Y,
Z
}
网友评论