我尝试过组合两个RotateArounds,然后读取鼠标偏移量,但是当它到达顶部时它会剧烈摇晃。我尝试将其锁定在90度,但还是不行。我还没有找到实现它的好方法,因为常规旋转也存在万向节锁定问题。
我希望能够实现类似于Unity编辑器中Alt+左键单击的轨道旋转,并且也是在顶部锁定90度,而不是到达顶部后继续轨道旋转,这样会导致屏幕倒转.
以下脚本附加到您的
Camera
对象:
Transform
旋转相机 using UnityEngine;
public class OrbitCamera : MonoBehaviour
{
[Tooltip("Transform of an object about which's center point camera should rotate")]
public Transform objToRotAbout;
[Tooltip("Rotation speed. Multiplication factor for mouse movement delta")]
public float rotationSpeed = 0.05f;
[Tooltip("Position of mouse in last frame")]
private Vector3 lastMousePos;
[Tooltip("Pose of camera in last frame")]
private Pose lastCamPose;
void Update()
{
// On mouse button down initially
if (Input.GetMouseButtonDown(0))
{
// Start with current mouse position
lastMousePos = Input.mousePosition;
}
// On mouse button pressed down continuously
if (Input.GetMouseButton(0))
{
// Rotate camera about object center
RotateCamera();
}
}
void RotateCamera()
{
// Calculate mouse movement delta & update last mouse position to current
Vector3 mouseDelta = Input.mousePosition - lastMousePos;
lastMousePos = Input.mousePosition;
// Calculate rotation amount based on mouse movement delta
float mouseX = mouseDelta.x * rotationSpeed;
float mouseY = mouseDelta.y * rotationSpeed;
// Store previous camera pose
lastCamPose = new Pose(transform.position, transform.rotation);
// Rotate camera about object
transform.RotateAround(objToRotAbout.position, Vector3.up, mouseX);
transform.RotateAround(objToRotAbout.position, transform.right, -mouseY);
// If camera upside down -> Revert to previous rotation
if (Vector3.Dot(transform.up, Vector3.down) > 0)
{
transform.SetPositionAndRotation(lastCamPose.position, lastCamPose.rotation);
}
}
}
目前,如果检测到相机颠倒,它会重置相机姿势。相反,您也可以先旋转占位符,检查它是否过度旋转,然后仅在满足条件时更新相机的姿势。但这种形式也确实有效。