首先创建一个物体,然后里面加上摄像机并且调整到相应的位置
在创建的物体上添加一个组件character controller
键盘控制移动代码
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
摄像机跟随鼠标移动代码
public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityHor = 9f;
public float sensitivityVert = 9f;
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 (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);
}
}
然后接下来是监听键盘脚本和第一人称鼠标移动效果,全部绑定在创建的物体上
这样就可以使用键盘和鼠标模拟第一人称视角移动的效果