创建一个可以自由移动的第一人称视角
人物通过WSAD进行前后左右移动,通过鼠标右键进行旋转
Step1:创建一个Player玩家,在节点下加两个子物体,一个摄像头和一个Capsule充当身体
Step2:创建一个脚本挂载在Player节点下,再在这个Player物体下加上Character Controller脚本
Step3:该脚本内容如下
using UnityEngine;
/// <summary>
/// 人物移动脚本
/// 直接引用Character的Move方法
/// </summary>
public class PlayerMove : MonoBehaviour
{
//键盘
public float speed = 30F;
public float jumpSpeed = 5.0F;
public float gravity = 5.0F;
private Vector3 moveDirection;
private CharacterController characterController;
//鼠标
public float mousespeed = 3f;
public float minmouseY = -45f;
public float maxmouseY = 45f;
public Transform playerCamera;
private Vector3 oldMousePos;
private Vector3 newMousePos;
private void OnEnable()
{
characterController = GetComponent<CharacterController>();
}
private void FixedUpdate()
{
if (Input.GetMouseButton(1))
{
//把当前右键鼠标点的位置先存储起来
newMousePos = Input.mousePosition;
//再把每一帧刚开始的位置和上一帧的位置做一个差值
Vector3 dis = newMousePos - oldMousePos;
//X,Y方向上位移的距离就是这个差值的x,y分量*鼠标移动速度
float angleX = dis.x * mousespeed;
float angleY = dis.y * mousespeed;
//然后再根据分量差值进行旋转
transform.Rotate(new Vector3(-angleY, 0, 0), Space.Self);
transform.Rotate(new Vector3(0, angleX, 0), Space.World);
}
if(characterController.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 = moveDirection.y - gravity * Time.deltaTime;
//使用characterController的Move方法对物体进行移动,参数就是移动方向 * 时间
characterController.Move(moveDirection * Time.deltaTime);
//更新鼠标的下一帧位置
oldMousePos = Input.mousePosition;
}
}
运行即可