unity 2022 使视角跟随小球,且右键拖动可调整视角,滚轮控制缩放
·
1.首先unity里添加一个小球
2.Main Camera里添加脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraControl : MonoBehaviour
{
//鼠标右键按下后移动鼠标控制视角围绕小球旋转,同时视角一直跟随小球。
public Transform target; // 要围绕的目标物体,要在unity中把物体拖进来
public float distance = 5.0f; // 距离
public float xSpeed = 120.0f; // 水平旋转速度
public float ySpeed = 120.0f; // 垂直旋转速度
private float x = 0.0f;
private float y = 0.0f;
//滚轮控制视角缩放
private Camera cam;
public float zoomSpeed = 10f; // 缩放速度
public float minFOV = 5f; // 最小视野角度
public float maxFOV = 150f; // 最大视野角度
// Start is called before the first frame update
void Start()
{
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
// 使摄像机始终面向目标
transform.LookAt(target);
transform.RotateAround(target.position, Vector3.up, -90); // 调整初始视角,使其面向目标但不完全正面朝上
//滚轮控制视角缩放
cam = GetComponent<Camera>();
}
// Update is called once per frame
void LateUpdate()
{
//鼠标右键按下后移动鼠标控制视角围绕小球旋转,同时视角一直跟随小球。
if (Input.GetMouseButton(1)) // 鼠标右键被按下
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, -90f, 90f); // 限制俯仰角,避免完全仰视或俯视
Quaternion rotation = Quaternion.Euler(y, x, 0);
Vector3 direction = new Vector3(0, 0, -distance);
Vector3 position = target.position + rotation * direction;
transform.rotation = Quaternion.Euler(y, x, 0);
transform.position = position;
}
else
{
Quaternion rotation = Quaternion.Euler(y, x, 0);
Vector3 direction = new Vector3(0, 0, -distance);
Vector3 position = target.position + rotation * direction;
transform.rotation = Quaternion.Euler(y, x, 0);
transform.position = position;
}
//滚轮控制视角缩放
float scroll = Input.GetAxis("Mouse ScrollWheel"); // 获取鼠标滚轮的滚动值
if (scroll != 0)
{
cam.fieldOfView += scroll * zoomSpeed; // 调整视野角度
cam.fieldOfView = Mathf.Clamp(cam.fieldOfView, minFOV, maxFOV); // 限制视野角度在最小和最大值之间
}
}
static float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
3.unity里把小球拖到Main Camera的脚本参数里。

更多推荐


所有评论(0)