private Vector3 depth; private Vector3 offset; public float sudu = 0.001f; private void OnMouseDown() { depth = Camera.main.WorldToScreenPoint(transform.position); Vector3 mousePosition = Input.mousePosition; mousePosition = new Vector3(mousePosition.x, mousePosition.y, depth.z); offset = transform.position - Camera.main.ScreenToWorldPoint(mousePosition); } private void OnMouseDrag() { Vector3 mousePosition = Input.mousePosition; mousePosition = new Vector3(mousePosition.x, mousePosition.z, depth.y); transform.Rotate(-Vector3.forward * (Camera.main.ScreenToWorldPoint(mousePosition) + offset).x * sudu); }这个代码怎么加上限制旋转的范围
时间: 2024-02-14 11:06:44 浏览: 64
你可以在`OnMouseDrag()`函数中添加限制旋转的范围的代码。例如,你可以使用Quaternion来限制旋转的角度。在`OnMouseDrag()`函数中,你可以将旋转的角度保存在一个变量中,然后在限制范围时,通过Quaternion来限制旋转的角度。
以下是一个示例代码,可以让物体只能在y轴上旋转:
```
private Vector3 depth;
private Vector3 offset;
public float sudu = 0.001f;
private float rotationY = 0f;
public float minY = 0f;
public float maxY = 360f;
private void OnMouseDown()
{
depth = Camera.main.WorldToScreenPoint(transform.position);
Vector3 mousePosition = Input.mousePosition;
mousePosition = new Vector3(mousePosition.x, mousePosition.y, depth.z);
offset = transform.position - Camera.main.ScreenToWorldPoint(mousePosition);
}
private void OnMouseDrag()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = new Vector3(mousePosition.x, mousePosition.z, depth.y);
float rotationX = -((Camera.main.ScreenToWorldPoint(mousePosition) + offset).x * sudu);
rotationY += ((Camera.main.ScreenToWorldPoint(mousePosition) + offset).y * sudu);
rotationY = Mathf.Clamp(rotationY, minY, maxY);
transform.rotation = Quaternion.Euler(new Vector3(rotationY, rotationX, 0));
}
```
在这个示例代码中,`rotationY`变量保存了物体在y轴上的旋转角度。在`OnMouseDrag()`函数中,我们通过修改`rotationX`和`rotationY`来计算旋转角度。同时,我们使用`Mathf.Clamp()`函数来限制`rotationY`的值在`minY`和`maxY`之间。最后,我们使用`Quaternion.Euler()`函数来将旋转角度转换为Quaternion,并将其应用于物体的旋转。
阅读全文