Unity为什么当我在X轴上移动对象时,Z轴会改变
本文关键字:对象 改变 移动 为什么 Unity | 更新日期: 2023-09-27 18:28:10
我正在创建一个游戏,在这个游戏中我将成为一个立方体。但当我在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/Vvector3.left/VVector3.forward等并乘以标量。当想要相乘时,使事情看起来更直观。