开发Unity3D的程序这么多年,反复会用到相机围绕目标物体旋转的脚本。
一般做法通过鼠标来控制,右键按住旋转,滚轮远近镜头,按住滚轮平移。
断断续续在网上和Unity官方案例以及某些商店里的插件带的脚本。都不是特别满意。
今天心血来潮,试着用ChatGPT给我生成了一个。发现基本上可用。而且实现路径也很简便,看来程序员用好它很重要啊。
下面把ChatGPT生成的代码贴出来,以备后续使用。
using UnityEngine;
public class CameraController2 : MonoBehaviour
{
public Transform target; // 要围绕旋转的目标点
public float distance = 5.0f; // 相机与目标点的初始距离
public float minDistance = 1.0f; // 相机与目标点的最小距离
public float maxDistance = 10.0f; // 相机与目标点的最大距离
public float xSpeed = 120.0f; // 水平旋转速度
public float ySpeed = 120.0f; // 垂直旋转速度
public float smoothTime = 0.3f; // 阻尼时间
public float disTanceSpeed = 1.0f;
public float moveSpeed = 1.0f; // 相机平移速度
private float x = 0.0f;
private float y = 0.0f;
private float xVelocity = 0.0f;
private float yVelocity = 0.0f;
private Vector3 distanceVelocity;
void Start()
{
// 初始化相机位置
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
}
void LateUpdate()
{
// 通过滚轮调整相机距离
distance -= Input.GetAxis("Mouse ScrollWheel") * disTanceSpeed;
distance = Mathf.Clamp(distance, minDistance, maxDistance);
if (Input.GetMouseButton(1))
{
// 通过鼠标控制相机旋转
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
// 限制垂直旋转角度
y = ClampAngle(y, -90, 90);
// Vector3.SmoothDamp(transform.position, position, ref distanceVelocity, smoothTime * Time.deltaTime);
}
// 计算相机位置和旋转角度
Quaternion rotation = Quaternion.Euler(y, x, 0);
// 平滑移动相机
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, smoothTime * Time.deltaTime);
Vector3 position = transform.rotation * new Vector3(0.0f, 0.0f, -distance) + target.position;
// 更新相机位置和旋转角度
transform.position = position;
if (Input.GetMouseButton(2))
{
float mouseX = Input.GetAxis("Mouse X") * moveSpeed * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * moveSpeed * Time.deltaTime;
Vector3 move = new Vector3(-mouseX, -mouseY, 0);
move = transform.localToWorldMatrix.MultiplyVector(move);
target.Translate(move, Space.World);
}
}
private float ClampAngle(float angle, float min, float max)
{
if (angle < -360.0f)
{
angle += 360.0f;
}
if (angle > 360.0f)
{
angle -= 360.0f;
}
return Mathf.Clamp(angle, min, max);
}
}