unity3d 移动

//直接改变位移
transform.position += Vector3.forward * Time.deltaTime * 5;

//使用Translate改变位移
transform.Translate(Vector3.forward * 5 * Time.deltaTime);

//使用插值
transform.position = Vector3.Lerp(transform.position,GameObject.Find("Sphere").transform.position,0.1f);//因为position一直都被更新到最新,相当于Lerp(1,2,0.5)返回1.5,然后变成Lerp(1.5,2,0.5)。

//使用轴
float h = Input.GetAxis("Horizontal");//-1,1
float v = Input.GetAxis("Vertical");//-1,1
transform.position += new Vector3(h,0,v)*Time.deltaTime*10;//匀速运动

//使用刚体
float h = Input.GetAxis("Horizontal");//-1,1
float v = Input.GetAxis("Vertical");//-1,1
GetComponent<Rigidbody>().AddForce(new Vector3(h,0,v)*Time.deltaTime*10);

//使用MoveTowards
transform.position = Vector3.MoveTowards(transform.position,GameObject.Find("Sphere").transform.position, 0.01f);

//使用CharacterController
GetComponent<CharacterController>().SimpleMove(new Vector3(0,0,1)*Time.deltaTime*100);

例如:摄像机跟随。
public class Test: MonoBehaviour
{
    public Transform cubePos;//cube的位置
    public float smoth;//摄像机移动速度
    Vector3 targetPos;//摄像机最终的位置
    private void Start()
    {
        transform.position = cubePos.position + Vector3.back * 10;//将摄像机移动到cube位置的后面一点
    }
    private void LateUpdate()
    {
        targetPos = cubePos.position + Vector3.back * 10;//摄像机最终的位置,即cube的位置+一个距离
        transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime* smoth);
    }
}

猜你喜欢

转载自blog.csdn.net/tran119/article/details/81513225