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>());
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)