Unity模型观察脚本
移动相机脚本,围绕物体实现缩放和旋转
加了SmoothDamp实现缓动
public class ViewAndOperate : MonoBehaviour
{
public GameObject target;
public float rotateSpeed;
public float zoomSpeed;
public float rotateSmoothTime; // 缓冲时间参考值
public float zoomSmoothTime; // 缩放平滑时间
private float currentDistance;
private float targetDistance;
private float zoomVelocity;
public float zoomMinDistance;
public float zoomMaxDistance;
public float zoomSize;//鼠标滚轮缩放尺度
private float currentAngle;
private float targetAngle;
private float angleVelocity;
public float pitchMin;
public float pitchMax;
private float targetPitch;
private float currentPitch;
private float pitchVelocity;
private void Start()
{
currentDistance = Vector3.Distance(transform.position, target.transform.position);
targetDistance = currentDistance;
}
private void Update()
{
float scrollInput = Input.GetAxis("Mouse ScrollWheel")* zoomSize;
if (Input.GetMouseButton(1))
{
float horizontalInput = Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime * 100;
float verticalInput = -Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime * 100;
targetAngle += horizontalInput;
targetPitch += verticalInput;
targetPitch = Mathf.Clamp(targetPitch, pitchMin, pitchMax);
}
float smoothAngle = Mathf.SmoothDamp(currentAngle, targetAngle, ref angleVelocity, rotateSmoothTime);
float deltaAngle = smoothAngle - currentAngle;
currentAngle = smoothAngle;
float smoothPitch = Mathf.SmoothDamp(currentPitch, targetPitch, ref pitchVelocity, rotateSmoothTime);
float deltaPitch = smoothPitch - currentPitch;
currentPitch = smoothPitch;
transform.RotateAround(target.transform.position, Vector3.up, deltaAngle);
transform.RotateAround(target.transform.position, transform.right, deltaPitch);
if (scrollInput != 0)
{
targetDistance = Mathf.Clamp(targetDistance - scrollInput * zoomSpeed, zoomMinDistance, zoomMaxDistance);
}
currentDistance = Mathf.SmoothDamp(currentDistance, targetDistance, ref zoomVelocity, zoomSmoothTime);
Vector3 zoomDirection = (transform.position - target.transform.position).normalized;
transform.position = target.transform.position + zoomDirection * currentDistance;
}
}