首页 > 移动平台 > 详细

Unity 物体移动方式

时间:2021-09-24 16:26:08      阅读:71      评论:0      收藏:0      [点我收藏+]

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 物体移动方式

原文:https://www.cnblogs.com/ZTianming/p/15310272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!