简体   繁体   English

Unity-为什么在 X 轴上移动对象时 Z 轴会发生变化?

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

I am creating a game in which I will be a cube.我正在创建一个游戏,其中我将成为一个立方体。 But when I move my cube on X axis the Z axis changes.但是当我在 X 轴上移动我的立方体时,Z 轴会发生变化。 I've also blocked the X, Y, Z rotation.我还阻止了 X、Y、Z 旋转。

My code:我的代码:

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);
        }
    }
}

It looks like you're applying movement in world space.看起来您正在世界空间中应用运动。 You likely want to apply it in object space.您可能希望将其应用于对象空间。 So you'll want to rotate the vector you generate by the objects transform.因此,您需要旋转由对象变换生成的矢量。 Something like:就像是:

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

Also, a couple of things to make your life easier:此外,还有一些事情可以让您的生活更轻松:

  • Look into the Input.GetAxis() stuff for doing input.查看Input.GetAxis()进行输入的内容。 Can ease your life for setting things up/configuring later.可以减轻您以后设置/配置的生活。

  • I like using Vector3.up/Vector3.left/Vector3.forward etc. and multiplying by a scalar.我喜欢使用 Vector3.up/Vector3.left/Vector3.forward 等并乘以标量。 Makes things look more intuitive when wanting to multiply.想要乘法时让事情看起来更直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM