您的位置:首页 > 其它

MMORPG中的相机跟随算法

2017-06-29 17:27 225 查看
先上代码

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()函数为相机拉近拉远
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: