Unity 摄像机围绕物体旋转
时间: 2023-05-16 22:06:20 浏览: 95
可以使用以下代码实现:
```
public class CameraController : MonoBehaviour {
public Transform target;
public float rotateSpeed = 5;
private Vector3 offset;
void Start () {
offset = target.position - transform.position;
}
void LateUpdate () {
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
target.Rotate(0, horizontal, 0);
float desiredAngle = target.eulerAngles.y;
Quaternion rotation = Quaternion.Euler(0, desiredAngle, 0);
transform.position = target.position - (rotation * offset);
transform.LookAt(target);
}
}
```
其中,target 是需要围绕旋转的物体,rotateSpeed 是旋转速度,offset 是相机与物体之间的距离。在 LateUpdate 函数中,我们通过获取鼠标水平移动的距离来旋转物体,然后计算出相机的位置和朝向。最后,我们使用 LookAt 函数来让相机始终朝向物体。