将如下代码添加到角色摄像机:html
public Transform player; // 在这里添加玩家角色. private float mouseX, mouseY; // 储存鼠标移动的值. private float xRotation; // 储存X轴的旋转. public float Sensitivity; // 鼠标灵敏度. private void Update() { // 获取鼠标移动的值. mouseX = Input.GetAxis("Mouse X") * Sensitivity * Time.deltaTime; mouseY = Input.GetAxis("Mouse Y") * Sensitivity * Time.deltaTime; // 控制X轴的旋转. xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -70, 70); // 控制Y轴的旋转. player.transform.Rotate(Vector3.up * mouseX); transform.localRotation = Quaternion.Euler(xRotation, 0, 0); }
首先,确保你的角色已经添加了角色控制器,并且它的范围覆盖了角色本体。
在角色中添加一个空物体,起名为GroundChenck,并将它移动到角色最下面的位置。
将如下代码添加到角色:3d
private CharacterController playerController; // 玩家角色控制器. public Transform groundCheck; // 地面检测点. private Vector3 direction; // 方向. private Vector3 velocity; // 加速度. private float horizontal, vertical; // 储存键值. public float moveSpeed; // 移动速度. public float jumpSpeed; // 起跳速度. public float gravity; // 重力. public float checkRadius; // 地面检测点半径. private bool onGround; // 是否在地面上. private void Start() { playerController = GetComponent<CharacterController>(); // 实例化玩家角色控制器. } private void Update() { // 检测角色是否碰到地面. onGround = Physics.CheckSphere(groundCheck.position, checkRadius); // 加速度归零. if (onGround && velocity.y < 0) { velocity.y = 0f; } // 赋值键值. horizontal = Input.GetAxis("Horizontal") * moveSpeed; vertical = Input.GetAxis("Vertical") * moveSpeed; // 角色移动. direction = transform.forward * vertical + transform.right * horizontal; playerController.Move(direction * Time.deltaTime); // 角色跳跃. if (Input.GetButtonDown ("Jump") && onGround) { velocity.y = jumpSpeed; } // 重力加速度. velocity.y -= gravity * Time.deltaTime; playerController.Move(velocity * Time.deltaTime); }