我正在尝试构建一个简单的游戏,用户可以在其中放置一些元素并四处移动它们。
我想要的是让用户可以根据自己的决定在特定轴上移动对象。
非常类似于 unity 中的移动小工具。
我知道如何使用鼠标拖动世界中的对象,但我如何在特定轴(例如 Z 轴)上移动。
我尝试读取“鼠标 X”值,但它只适用于特定视角,如果我从不同角度看对象,对象将无法正确移动。
我做的是这样的:
private void OnMouseDrag()
{
transform.Translate(moveAxis * Input.GetAxis("Mouse X");
}
其中 moveAxis
是代表轴的 Vector3
,脚本附加到箭头 gizmo。
最佳答案
这是一种方法:
转换 moveAxis
从本地空间到屏幕空间的方向。确保你有一个缓存 Camera
字段/变量,因为调用 Camera.main
和/或 GetComponent<Camera>
是一个缓慢的操作:
// Get world direction from moveAxis
Vector3 worldDirection = transform.TransformDirection(moveAxis);
Vector2 screenDirection = camera.WorldToScreenPoint(worldDirection + transform.position)
- camera.WorldToScreenPoint(transform.position);
// optionally, normalize the vector in screen space.
// screenDirection.Normalize();
如果您不希望屏幕上轴的角度影响拖动的速度,您可以标准化屏幕方向。您可能不想对其进行标准化,但如果您想要不同的感觉,请尝试一下。
然后,计算坐标轴方向与鼠标移动的点积,计算出一个量级:
Vector2 mouseMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
float translateMagnitude = Vector2.Dot(mouseMovement, screenDirection);
mouseMovement.x
左边必须为负,右边必须为正,mouseMovement.y
向下必须为负,向上必须为正。如果任一轴反转,则将该轴的值乘以 -1f
.
这边,translateMagnitude
如果鼠标沿屏幕空间中的轴方向移动,则为正,如果向其移动则为负。
然后,将幅度乘以一些可配置的灵敏度因子,然后乘以 Translate
的轴向量调用:
public float translateSensitivity;
...
transform.Translate(moveAxis * translateSensitivity * translateMagnitude);
关于c# - 使用鼠标光标在特定轴上拖动 3D 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57380013/