【发布时间】:2021-10-25 09:12:57
【问题描述】:
我正在尝试创建模仿统一场景编辑器行为的相机移动,您可以在其中通过 2d 鼠标移动围绕场景执行球形旋转。到目前为止,在给定 x 或 y 移动的情况下,相机正在正确旋转,但是对角拖动会导致相机围绕其相对 z 轴旋转,直到它被锁定。我不能强迫相机相对于世界向上看原点,因为那样它就不能倒置旋转
这是我附加到相机的脚本
using UnityEngine;
public class MainCamera : MonoBehaviour
{
Vector2 startingPosition;
Vector2 mousePosition;
Vector3 orthogonalCameraVector;
float degreesPerUnitWidth = 180f / Screen.width;
float degreesPerUnitHeight = 180f / Screen.height;
float cameraRadius = 10;
void Start()
{
transform.position = new Vector3(0, 0, -cameraRadius);
transform.LookAt(Vector3.zero);
orthogonalCameraVector = -Vector3.left;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);
startingPosition = mousePosition;
var mouseDelta = startingPosition - input;
var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
var rotation = xzRotation * yRotation;
orthogonalCameraVector = rotation * orthogonalCameraVector;
transform.position = rotation * transform.position;
transform.rotation = rotation * transform.rotation;
mousePosition = Input.mousePosition;
}
}
}
【问题讨论】:
标签: unity3d