Unity 物体移动方式

Unity 物体移动方式

直接移动

obj.transform.position = new Vector3(0, 0, 0);

obj.transform.position += Vector3.forward * moveSpeed * Time.deltaTime;
var destination = new Vector3(0, 0, 0);

obj.transform.position = obj.transform.position + (destination - obj.transform.position).normalized * speed;

Vector3

// MoveTowards
obj.transform.position = Vector3.MoveTowards(from, to, duration);
// Lerp数学插值,
obj.transform.position = Vector3.Lerp(from, to, duration);

transform.translate

使用协程 + AnimationCurve

实现自定义运动轨迹

public AnimationCurve curve;

IEnumerator move(GameObject obj, Vector3 from, Vector3 to, float perTime)
        {
            float percent = 0;
           
            Debug.LogFormat("UIForwardItems.move obj name:{0}, from:{1}, to:{2}", obj.name, from, to);
            while (percent < 1)
            {
                percent += Time.deltaTime / perTime;
               
                obj.transform.position = Vector3.Lerp(from, to, curve.Evaluate(percent));
                // 另一种Lerp
                //obj.transform.position = Vector3.LerpUnclamped(from, to, curve.Evaluate(percent));
                yield return null;
            }

           
        }

UITween

public void move(GameObject obj, Vector3 from, Vector3 to, bool useWorld, float duration, float delay, EventDelegate.Callback onFinish)
{
    TweenPosition tween = ((GameObject)obj).GetComponent<TweenPosition>();
    
    tween.from = from;
    tween.to = to;
    tween.useWorldSpace = useWorld;
    tween.duration = duration;
    tween.delay = delay;
    tween.style = duration < 0 ? UITweener.Style.PingPong : UITweener.Style.Once;
    tween.ResetToBeginning();
    tween.SetOnFinished(onFinish);
    tween.PlayForward();
}

使用DOTween插件

//花费0.5秒, 移动到111
transform.doMove(Vector3.one, 0.5f);

注:

如果要移动拥有LayoutGroup组件下的子物体,

LayoutGroup排版计算是在下一帧才进行,需要强制进行刷新,实现布局实时计算,具体代码如下:

LayoutRebuilder.ForceRebuildLayoutImmediate(this.GetComponent<RectTransform>());

Unity 物体移动方式

上一篇:算法学习


下一篇:如何解决IOS 15提示“此App的开发者需要更新APP以在此IOS版本上正常工作”, 无法打开安装的APP的问题