Unity 点击按钮摄像机围绕物体旋转指定角度
时间: 2023-05-16 15:06:21 浏览: 1064
unity C#以物体为中心旋转相机
可以使用以下代码实现:
```csharp
public class RotateCamera : MonoBehaviour
{
public Transform target;
public float rotationSpeed = 5.0f;
public float maxRotationAngle = 90.0f;
private Vector3 offset;
void Start()
{
offset = transform.position - target.position;
}
void LateUpdate()
{
float horizontal = Input.GetAxis("Horizontal") * rotationSpeed;
float vertical = Input.GetAxis("Vertical") * rotationSpeed;
transform.RotateAround(target.position, Vector3.up, horizontal);
Vector3 cameraPosition = transform.position;
Vector3 targetPosition = target.position + offset;
Vector3 direction = cameraPosition - targetPosition;
Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
float angle = Quaternion.Angle(transform.rotation, rotation);
if (angle < maxRotationAngle)
{
transform.rotation = rotation;
}
}
}
```
这段代码实现了一个摄像机围绕物体旋转的效果,可以通过水平和垂直输入控制旋转方向和速度,同时限制了最大旋转角度。
阅读全文