Unity3D之如何讓對象沿着自身座標系移動

在寫遊戲中,你肯定想讓物體沿着自身座標系移動,如何做呢?

通過直接改變對象座標實現:

法一:

自身z軸方向移動:

transform.position += transform.forward * Input.GetAxis("Vertical") * Time.deltaTime;

自身x軸方向移動:

transform.position += transform.right * Input.GetAxis("Vertical") * Time.deltaTime;

 自身y軸方向移動:

transform.position += transform.up * Input.GetAxis("Vertical") * Time.deltaTime;

法二:

自身z軸方向移動:

transform.Translate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self);

 自身x軸方向移動:

transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self);

  自身y軸方向移動:

transform.Translate(Vector3.up * Time.deltaTime * Input.GetAxis("Vertical"), Space.Self);

 用速度來控制對象的移動:

要使對象有速度可以,肯定要先添加<Rigidbody>組件

下面是代碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour {

    public float rotationSpeed;
    public float MoveSpeed;

    void Update () {
        if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
        {
            transform.GetComponent<Rigidbody>().velocity = transform.forward * Input.GetAxis("Vertical") * MoveSpeed + transform.right * Input.GetAxis("Horizontal") * MoveSpeed;
        }

        transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X"), 0) * rotationSpeed, Space.Self);
    }
}

用力來控制對象的移動: 

下面是代碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour {

    public float rotationSpeed;
    public float MoveSpeed;

    void Update () {
        if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
        {
            transform.GetComponent<Rigidbody>().AddForce(transform.forward * Input.GetAxis("Vertical") * MoveSpeed + transform.right * Input.GetAxis("Horizontal") * MoveSpeed);
        }

        transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X"), 0) * rotationSpeed, Space.Self);
    }
}

 上面兩個都是沿着水平方向移動的,當然你也可以通過實際情況進行更改。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章