|
22.gif
方式一
Transform.Translate(moveDir * Time.deltaTime * speed ,Space relativeTo)transform.position += moveDir * Time.deltaTime * speed
需要注意的是:moveDir表示移动方向,可以是Vector3.forward,也可以是endPosition-startPosition;
using UnityEngine;using UnityEngine.UI;public class MoveTest : MonoBehaviour{ Vector3 endPosition = new Vector3(3, 3, 3); Vector3 startPosition ; bool isStart = false; float speed = 1; Vector3 moveDir; float distance; public Button btn; void Start() { startPosition = transform.position; endPosition.y = transform.position.y; moveDir = endPosition - startPosition; distance = Vector3.Distance(startPosition, endPosition); btn.onClick.AddListener(StartRun); } public void StartRun() { transform.position = startPosition; isStart = true; } void Update() { if (isStart) { //下面3行代码一样的效果 transform.Translate(moveDir * Time.deltaTime * speed, Space.World); //transform.position += moveDir * Time.deltaTime * speed; float dis = Vector3.Distance(startPosition, transform.position); if (dis >= distance) { isStart = false; } } }}方式二
Vector3 vec = Vector3.Lerp(startPosition, endPosition, progress);transform.position = vec;
需要注意的是,progress是一个[0-1]之间的值,如果progress=0.1,那么vec的值就在两点的1/10位置处;如果progress=0.2,那么vec的值就在两点的2/10位置处;
using UnityEngine;using UnityEngine.UI;public class Move_Lerp : MonoBehaviour{ Vector3 endPosition = new Vector3(2, 2, 2); Vector3 startPosition; bool isStart = false; float speed = 1; float totalTime; float currentTime; public Button btn; void Start() { startPosition = transform.position; endPosition.y = transform.position.y; totalTime = Vector3.Distance(startPosition, endPosition) / speed; btn.onClick.AddListener(StartRun); } void StartRun() { transform.position = startPosition; isStart = true; currentTime = 0; } void Update() { if (isStart) { currentTime += Time.deltaTime; Vector3 vec = Vector3.Lerp(startPosition, endPosition, currentTime / totalTime); transform.position = vec; } }}方式三
transform.position = Vector3.MoveTowards(currentPosition, targetPosition, Time.deltaTime * speed);
需要注意的是currentPosition表示的是自己的实时位置
using UnityEngine;using UnityEngine.UI;public class MoveToTowards : MonoBehaviour{ Vector3 endPosition = new Vector3(3, 3, 3); Vector3 startPosition; bool isStart = false; float speed = 1; public Button btn; void Start() { startPosition = transform.position; endPosition.y = transform.position.y; btn.onClick.AddListener(StartRun); } public void StartRun() { transform.position = startPosition; isStart = true; } void Update() { if (isStart) { transform.position = Vector3.MoveTowards(transform.position, endPosition, Time.deltaTime * speed); } }} |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|