经历了几个版本的修改,终于拥有了一份很适合自己使用的第一人称控制脚本了,是在网上教程上修改的,之前借鉴的版本是鼠标移动能控制视野各种方向旋转,但是我不需要实时旋转。有时候会移动鼠标点击物体,视野跟随鼠标动就很麻烦。
以下脚本实现的功能是按WASD控制前后左右移动,鼠标左键点击可以进行操作,按下鼠标右键可以进行视野旋转,且相机一直是处于水平,不会倾斜。
move脚本,控制前后左右移动
public class Move : MonoBehaviour
{
public CharacterController controller;
public Rigidbody rigidbody;
public float speed = 1;
// Use this for initialization
void Start()
{
rigidbody = this.GetComponent<Rigidbody>();
controller = this.GetComponent<CharacterController>();
}
//Move
// Update is called once per frame
void Update()
{
//Move
if (Input.GetKey("a"))
controller.SimpleMove(controller.transform.right * -speed);
//controller.SimpleMove(transform.right * -speed);
if (Input.GetKey("d"))
controller.SimpleMove(controller.transform.right * speed);
if (Input.GetKey("w"))
controller.SimpleMove(controller.transform.forward * speed);
if (Input.GetKey("s"))
controller.SimpleMove(controller.transform.forward * -speed);
}
}
Mouselook脚本控制鼠标点击和相机旋转
public class Mouselook : MonoBehaviour
{
public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityHor = 1f;
public float sensitivityVert = 1f;
public float minmumVert = -45f;
public float maxmumVert = 45f;
private float _rotationX = 0;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(1)) {
if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
}
else if (axes == RotationAxes.MouseY)
{
_rotationX = _rotationX - Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minmumVert, maxmumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(-_rotationX, rotationY, 0);
}
else
{
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minmumVert, maxmumVert);
float delta = Input.GetAxis("Mouse X") * sensitivityHor;
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(-_rotationX, rotationY, 0);
}
}
}
}