MMORPG中的相机跟随算法
2017-06-29 17:27
225 查看
先上代码
此代码使用了3D数学中的sin和cos函数
计算了3D空间中相机与主角之间的位置关系
使得相机可以围绕主角旋转
从而360度无死角观察主角
target表示主角物体
SetTarget可以获取名为“cameraPoint”的主角物体
Rotate()函数为相机旋转
Roll()函数为相机上下角度调整
Zoom()函数为相机拉近拉远
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { //摄像机与主角的直线距离 public float distance = 15; //横向角度 public float rot = 0; //纵向角度 public float roll = 30f*Mathf.PI * 2 / 360; //目标物体 public GameObject target; //横向旋转速度 public float rotSpeed = 0.2f; //纵向旋转速度 public float rollSpeed = 0.2f; //纵向角度范围 public float maxRoll = 70f * Mathf.PI * 2 / 360; public float minRoll = -10f * Mathf.PI * 2 / 360; //鼠标滚动距离范围 public float maxDistance = 22f; public float minDistance = 5f; //距离变化速度 public float zoomSpeed = 0.2f; //设置相机焦点目标 public void SetTarget(GameObject target) { if (target.transform.Find("cameraPoint") != null) this.target = target.transform.Find("cameraPoint").gameObject; else this.target = target; } private void Rotate() { float w = Input.GetAxis("Mouse X") * rotSpeed; rot -= w; } private void Roll() { float w = Input.GetAxis("Mouse Y") * rollSpeed * 0.5f; roll -= w; if (roll > maxRoll) roll = maxRoll; if (roll < minRoll) roll = minRoll; } private void Zoom() { if (Input.GetAxis("Mouse ScrollWheel") > 0) { if (distance > minDistance) distance -= zoomSpeed; } else if (Input.GetAxis("Mouse ScrollWheel") < 0) { if (distance < maxDistance) distance += zoomSpeed; } } private void LateUpdate () { if (target == null) return; if (Camera.main == null) return; Rotate(); Roll(); Zoom(); Vector3 targetPos = target.transform.position; Vector3 cameraPos; float d = distance * Mathf.Cos(roll); float height = distance * Mathf.Sin(roll); cameraPos.x = targetPos.x + d * Mathf.Cos(rot); cameraPos.z = targetPos.z + d * Mathf.Sin(rot); cameraPos.y = targetPos.y + height; Camera.main.transform.position = cameraPos; Camera.main.transform.LookAt(target.transform); } }
此代码使用了3D数学中的sin和cos函数
计算了3D空间中相机与主角之间的位置关系
使得相机可以围绕主角旋转
从而360度无死角观察主角
target表示主角物体
SetTarget可以获取名为“cameraPoint”的主角物体
Rotate()函数为相机旋转
Roll()函数为相机上下角度调整
Zoom()函数为相机拉近拉远
相关文章推荐
- Unity3D 相机跟随算法
- Unity 2D游戏相机跟随
- 学习Unity3D之探照灯效果和相机跟随。
- Unity3D 相机跟随主角移动
- 深度相机的人物检测、分割、跟踪算法,openNI的NITE采用的算法,kinect,华硕xtion
- unity之--相机跟随移动
- unity 常用的几种相机跟随
- OpenCV 图像白平衡算法(相机自动白平衡)
- LoL、DOTA、王者荣耀类游戏小地图注册及相机的跟随
- 相机跟随和鼠标滚轮控制缩放
- Unity3D-相机跟随抖动
- Unity3D控制物体前后左右移动、旋转及相机跟随
- Unity 常用的几种相机跟随
- Unity 3D 泰课网小球移动 相机跟随
- 相机中白平衡的算法模拟实现
- Unity3d--实现第三人称视角(相机跟随)
- unity笔记 0 - 添加物体,预制体;施加力;移动物体,旋转物体;相机跟随;禁用物体
- SurvivalShooter学习笔记(一.相机跟随)
- 影子跟随算法
- 一种相机震荡算法