Vector3.Lerp:http://www.ceeger.com/Script/Vector3/Vector3.Lerp.html
手冊中描述的不是很詳細,什么叫“按照數字t在from到to之間插值”???t代表什么鬼?還得自己測試一下才知道
我以前這樣用過:
from.position = Vector3.Lerp(from.position, to.position, Time.deltaTime);
或者想要快一些我就這樣:
from.position = Vector3.Lerp(from.position, to.position, Time.deltaTime * 2f);
不知道大家有沒有像我這樣用過!第三個參數取值范圍0~1,其實就是距離百分比,比如填0.5f,那么就是取A點到B點的中間位置
如果像我上面那種方法去使用,就會導致物體在移動的時候會越來越慢
假設A點到B點距離是10,第三個參數t我填0.5f,那么插值一次后距離就減少了一半,在執行一次,又減少了一半距離
當然,如果需求就是這樣的話直接用就行了,但是如果需求是勻速平滑到某點,這咋辦呢?
既然都知道第三個參數其實就是距離百分比了,那我們自己算一下距離百分比不就行了嗎?
1 public Transform from; 2 public Transform to; 3 public float mMoveTime; 4 private Vector3 mStartPos; 5 private float t; 6 7 private bool mIsPlay = false; 8 9 void Update() 10 { 11 if (!mIsPlay) 12 return; 13 14 t += 1f / mMoveTime * Time.deltaTime; 15 from.position = Vector3.Lerp(mStartPos, to.position, t); 16 } 17 18 void OnGUI() 19 { 20 if(GUI.Button(new Rect(100,100,100,30),"play")) 21 { 22 mStartPos = from.position; 23 mIsPlay = true; 24 } 25 }
看了上面的介紹,相信對Vector3.Lerp有些了解了!
如果我想要他移動到指定位置后繼續保持勻速運動怎么做呢?也許你會說用Vector3.Lerp完全可以啊!
可是你別忘了,它的取值范圍是0~1,也就是說>1的值它會忽略掉,我測試了一下的確如此
那看來只能自己實現了!這其實很簡單,下面我們就來自己實現一遍
1 void Update() 2 { 3 if (!mIsPlay) 4 return; 5 6 t += 1f / mMoveTime * Time.deltaTime; 7 //from.position = Vector3.Lerp(mStartPos, to.position, t); 8 from.position = mStartPos + (to.position - mStartPos) * t; 9 }