赞
踩
目录
学习笔记,仅供学习,不做商用,如有侵权,联系我删除即可。
参考博文:
Unity 自由视角的惯性旋转https://haiyue.blog.csdn.net/article/details/123297435
1.1 相机环绕角色旋转
使用Transform.RotateAround,axis为轴,方向旋转
Declaration
public void RotateAround(Vector3 point, Vector3 axis, float angle);
Description
Rotates the transform about
axis
passing throughpoint
in world coordinates byangle
degrees.This modifies both the position and the rotation of the transform.
- using UnityEngine;
-
- //Attach this script to a GameObject to rotate around the target position.
- public class Example : MonoBehaviour
- {
- //Assign a GameObject in the Inspector to rotate around
- public GameObject target;
-
- void Update()
- {
- // Spin the object around the target at 20 degrees/second.
- transform.RotateAround(target.transform.position, Vector3.up, 20 * Time.deltaTime);
- }
- }
1.2 LookAt()函数
根据官方的文档描述,该函数的功能是,旋转自身,使得当前对象的正z轴指向目标对象target所在的位置。
而对于worldUp的描述是,在完成上面的旋转之后,继续旋转自身,使得当前对象的正y轴朝向与worldUp所指向的朝向一致.
可以使用LookAt函数修正,让相机正确地朝向角色
按下鼠标右键时,每一帧都获取鼠标的位置,通过两帧之间的鼠标位置之差,即可求得两帧之间的鼠标速度。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class PlayerTransform : MonoBehaviour
- {
- public Transform HeadTransform;
- private float CamDepthSmooth = 200f;
- private Vector3 RelativePos;
-
- // Start is called before the first frame update
- void Start()
- {
- RelativePos = transform.position - HeadTransform.position;
- }
-
- // Update is called once per frame
- void Update()
- {
- transform.position = HeadTransform.position + RelativePos;
- DragToRotateView_Distance();
- // 视角的拉近和放远
- if ((Input.mouseScrollDelta.y < 0 && Camera.main.fieldOfView >= 3) ||
- (Input.mouseScrollDelta.y > 0) && Camera.main.fieldOfView <= 80)
- {
- Camera.main.fieldOfView += Input.mouseScrollDelta.y * CamDepthSmooth * Time.deltaTime;
- }
- }
-
- /* 通过鼠标拖拽距离来旋转视角 */
- Vector3 Point1;
- Vector3 Point2;
- // 旋转每度在一帧中需要拖拽的距离
- int DragDistancePerAngle = 8;
- void DragToRotateView_Distance()
- {
-
- if (Input.GetMouseButtonDown(1)) // 按下右键的瞬间记录起始位置
- {
- Point1 = Input.mousePosition;
- //StartPoint = Point1;
- }
-
- if (Input.GetMouseButton(1)) // 按下右键每一帧都执行
- {
- Point2 = Input.mousePosition;
- float dx = Point2.x - Point1.x;
- float dy = Point2.y - Point1.y;
-
- float AngleX = dx / DragDistancePerAngle;
- float AngleY = dy / DragDistancePerAngle;
-
- transform.RotateAround(HeadTransform.position, Vector3.up, AngleX);
- transform.RotateAround(HeadTransform.position, -transform.right, AngleY);
- transform.LookAt(HeadTransform);
-
- RelativePos = transform.position - HeadTransform.position;
-
- Point1 = Point2;
- Point2 = Vector3.zero;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。