我已经开始学习 Unity,但我不确定局部坐标和全局坐标是如何工作的。我有两个脚本。
First(负责角色移动(A,W,S,D)):
public class Move : MonoBehaviour
{
// Start is called before the first frame update public float speed = 6.0f; private CharacterController _charController; public float gravity = -9.8f;
// Update is called once per frame
void Start()
{
_charController = GetComponent<CharacterController>();
}
void Update()
{
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed);
movement.y = gravity;
movement *= Time.deltaTime;
//movement = transform.TransformDirection(movement);
_charController.Move(movement);
}
}
第二个(鼠标旋转):
public class MouseLook : MonoBehaviour
{
public enum RotationAxes {MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityHor = 9.0f;
public float sensitivityVert = 9.0f;
private float _rotationX = 0;
public float minimumVert = -900f;
public float maximumVert = 900f;
void Start()
{
Rigidbody body = GetComponent<Rigidbody>();
if (body != null)
body.freezeRotation = true;
}
void Update()
{
if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
}
else if (axes == RotationAxes.MouseY)
{
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
else
{
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * sensitivityHor;
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}
我不清楚局部坐标系和全局坐标系在这里是如何工作和相互作用的。当我们从局部坐标系转换到全局坐标系时到底发生了什么
movement = transform.TransformDirection(运动);
我的鼠标旋转在这里是如何工作的也不完全清楚。正如我所见,它在本地坐标系中,那么代码如何工作,以便当您转动鼠标时,您将根据转动的位置直接向前移动?
总而言之,我不明白从局部坐标系到全局坐标系的转换在这里是如何工作的,这些坐标系是如何自己工作的,为什么要从一个坐标系转换到另一个坐标系?以及依赖性如何工作:你转动鼠标的方向,就是你直走的方向。
我现在看的书好像解释的不是很好,希望能得到一些帮助
局部计算是相对于它们正在计算的对象,而全局(或
world
)计算总是固定在世界上。例如,假设您是游戏中的角色;你在海滩上,面向东方,面向大海。你自己的Z前锋是朝东的,但是世界上的Z前锋总是朝北的,不管你面向什么方向,就像一个指南针。所以:世界 = 固定常数,本地 = 相对于你。您可以根据需要使用这些 - 例如,如果您正在编写让汽车前进的脚本,您可能会使用本地 transform.forward
因为您想朝汽车面向的任何方向行驶。如果你想要指向北方的东西,你可能会使用 world Vector3(0, 0, 1)
因为它是一个固定点。
很难从你的脚本中判断出你需要哪个,但你几乎肯定应该避免直接分配轮换,例如
localEulerAngles =
支持内置方法,例如transform.rotation =
(https://docs.unity3d.com/ScriptReference/Transform.html)。