簡體   English   中英

Unity-為什么在 X 軸上移動對象時 Z 軸會發生變化?

[英]Unity-Why is Z axis changing when I move an object on X axis?

我正在創建一個游戲,其中我將成為一個立方體。 但是當我在 X 軸上移動我的立方體時,Z 軸會發生變化。 我還阻止了 X、Y、Z 旋轉。

我的代碼:

using UnityEngine;
using System.Collections;

public class CubeControl : MonoBehaviour {
    private Vector3 input;

    void Update () {
        if(Input.GetKey(KeyCode.D)){
            input = new Vector3(25, 0, 0);
            rigidbody.AddForce(input);
        }
        if(Input.GetKey(KeyCode.A)){
            input = new Vector3(-25, 0, 0);
            rigidbody.AddForce(input);
        }
        if(Input.GetKey(KeyCode.W)){
            input = new Vector3(0, 0, 25);
            rigidbody.AddForce(input);
        }
        if(Input.GetKey(KeyCode.S)){
            input = new Vector3(0, 0, -25);
            rigidbody.AddForce(input);
        }
    }
}

看起來您正在世界空間中應用運動。 您可能希望將其應用於對象空間。 因此,您需要旋轉由對象變換生成的矢量。 就像是:

Vector3 input = new Vector3(25,0,0);
input = this.transform.rotation * input;
rigidbody.AddForce(input);

此外,還有一些事情可以讓您的生活更輕松:

  • 查看Input.GetAxis()進行輸入的內容。 可以減輕您以后設置/配置的生活。

  • 我喜歡使用 Vector3.up/Vector3.left/Vector3.forward 等並乘以標量。 想要乘法時讓事情看起來更直觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM