之前发表过第三人称游戏人物角色控制,但是那是要配合摄像机来使用的,摄像的代码怎么写呢,直接上代码吧
using UnityEngine;
using System.Collections;
public class CameraControl : MonoBehaviour
{
public GameObject target;
public float ZoomSpeed = 30;//镜头缩放速率
// public float MovingSpeed = 1;//镜头移动速率
public float RotateSpeed = 1; //镜头旋转速率
public float distance = 20;//设置距离角色的距离
public float Mindistance = 4;//设置摄像机与角色最小距离
public float Maxdistance = 12;//设置摄像机与角色最大距离
public float ViewAngle = 30;//设置镜头斜视的角度
float delta_rotation_x, delta_rotation_y;
private Vector3 offsetPosition;
/*最好能设置个状态机,玩家运动时摄像机不可操作Input.GetAxis("Mouse Y")*/
void Start()
{
//重置摄像机位置
if (target)
{
transform.rotation = Quaternion.Euler(ViewAngle, target.transform.rotation.eulerAngles.y, 0);
transform.position = transform.rotation * new Vector3(0, 0, -distance) + target.transform.position;//通过计算初始值得到摄像机的坐标
}
else { Debug.Log("没有绑定人物"); }
}
void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") != 0)//鼠标滚轮操作视角缩放
{
if (distance < Mindistance-1) { distance = Mindistance; }
if (distance > Maxdistance) { distance = Maxdistance-1; }
distance += -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
if (distance < Maxdistance && distance > Mindistance - 1)//限定滚轮缩放范围
{
transform.position = transform.rotation * new Vector3(0, 0, -distance) + target.transform.position;
}
//SendMessage("NewgetInput", distance);
}
if
(Input.GetMouseButton(1))//按照鼠标右键滑动鼠标控制视角偏移量
{
delta_rotation_x = Input.GetAxis("Mouse X") * RotateSpeed;
delta_rotation_y = -Input.GetAxis("Mouse Y") * RotateSpeed;
transform.Rotate(0, delta_rotation_x, 0, Space.World);
if (transform.rotation.eulerAngles.x >= 80)
{
transform.eulerAngles = new Vector3(79, target.transform.rotation.eulerAngles.y, 0);
}
if (transform.rotation.eulerAngles.x <= 3)
{
transform.eulerAngles = new Vector3(4, target.transform.rotation.eulerAngles.y, 0);
}
if (transform.rotation.eulerAngles.x > 3 && transform.rotation.eulerAngles.x < 80)
{
transform.Rotate(delta_rotation_y, 0, 0);
}
transform.position = transform.rotation * new Vector3(0, 0, -distance) + target.transform.position;
transform.LookAt(target.transform);
}
transform.position = transform.rotation * new Vector3(0, 0, -distance) + target.transform.position;
transform.LookAt(target.transform);
}
}
总结和注意事项
1、脚本挂载在摄像机上,摄像机使用默认设置透视摄像机
2、当玩家在运动时同时操作摄像机Y方向上的视角偏移时,会出现视角晃动,修改部分代码,或者设置玩家移动时不可操作摄像机
3、限定滚轮缩放范围虽然能达到目的,但是采用的是最大、最小值重新赋值的方法,会导致视角不平滑