72 lines
2.1 KiB
C#
72 lines
2.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
using static UnityEngine.GraphicsBuffer;
|
|
|
|
public class PlayerController : MonoBehaviour
|
|
{
|
|
public Camera mainCamera;
|
|
public float rotationSpeed = 5f;
|
|
public float zoomSpeed = 10f;
|
|
public float minFov = 20f;
|
|
public float maxFov = 120;
|
|
|
|
private Vector3 lastMousePosition; public float distance = 5f;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
if (mainCamera == null)
|
|
{
|
|
mainCamera = Camera.main;
|
|
}
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
HandleRotation();
|
|
|
|
HandleZoom();
|
|
}
|
|
|
|
// 通过鼠标拖动来旋转物体
|
|
void HandleRotation()
|
|
{
|
|
if (Input.GetMouseButtonDown(0)) // 鼠标左键按下时记录鼠标位置
|
|
{
|
|
lastMousePosition = Input.mousePosition;
|
|
}
|
|
|
|
if (Input.GetMouseButton(0)) // 鼠标左键保持按下状态时
|
|
{
|
|
Vector3 delta = Input.mousePosition - lastMousePosition; // 获取鼠标的移动距离
|
|
|
|
float rotX = delta.x * rotationSpeed * Time.deltaTime; // 水平旋转
|
|
float rotY = -delta.y * rotationSpeed * Time.deltaTime; // 垂直旋转
|
|
|
|
// 计算新的旋转角度
|
|
mainCamera.transform.RotateAround(transform.position, Vector3.up, rotX); // 水平绕目标物体旋转
|
|
mainCamera.transform.RotateAround(transform.position, mainCamera.transform.right, rotY); // 垂直绕目标物体旋转
|
|
|
|
// 更新摄像机的旋转后的位置
|
|
Vector3 direction = (mainCamera.transform.position - transform.position).normalized; // 获取摄像机指向目标物体的方向
|
|
mainCamera.transform.position = transform.position + direction * distance; // 根据旋转角度调整摄像机的位置
|
|
|
|
lastMousePosition = Input.mousePosition; // 更新上一帧的鼠标位置
|
|
}
|
|
}
|
|
|
|
|
|
void HandleZoom()
|
|
{
|
|
float scrollInput = Input.GetAxis("Mouse ScrollWheel");
|
|
if (scrollInput != 0)
|
|
{
|
|
|
|
mainCamera.fieldOfView = Mathf.Clamp(mainCamera.fieldOfView - scrollInput * zoomSpeed, minFov, maxFov);
|
|
}
|
|
}
|
|
}
|