使用鼠标光标在特定轴上拖动 3D 对象

Drag 3D object on specific axis using the mouse cursor

我正在尝试构建一个简单的游戏,用户可以在其中放置一些元素并四处移动它们。

我想要的是让用户可以根据his/her决定在特定轴上移动对象。

非常像 unity 中的移动小工具。

我知道如何用鼠标拖动世界中的对象,但我如何在特定轴(例如 Z 轴)上移动。

我尝试读取 "Mouse X" 值,但它只适用于特定视角,如果我从不同角度看物体,物体将无法正确移动。

我做的是这样的:

private void OnMouseDrag()
{
   transform.Translate(moveAxis * Input.GetAxis("Mouse X");
}

其中 moveAxis 是代表轴的 Vector3,脚本附加到箭头 gizmo。

这是一种方法:

moveAxis 方向从本地 space 转换为屏幕 space。确保你有一个缓存 Camera field/variable,因为调用 Camera.main and/or 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

这样,如果鼠标在屏幕 space 的轴方向上移动,translateMagnitude 将为正值,如果向相反方向移动,则为负值。

然后,将幅度乘以一些可配置的灵敏度因子,然后乘以 Translate 调用的轴向量:

public float translateSensitivity; 

...

transform.Translate(moveAxis * translateSensitivity * translateMagnitude);