前情提要

1.创建Capsule,为其挂载如下物体及组件。
挂载物体:Main Camera、GroundCheck(空物体)
image.pngimage.png
2.为Main Camera添加摄像机代码(CameraController)。
image.png

摄像机(角色)视角

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CameraController : MonoBehaviour {
  5. public Transform player;
  6. private float mouseX, mouseY; //获取鼠标移动的值
  7. public float mouseSensitivity; //鼠标灵敏度
  8. public float xRotation;
  9. private void Start () {
  10. Cursor.lockState = CursorLockMode.Locked;
  11. }
  12. private void Update () {
  13. mouseX = Input.GetAxis ("Mouse X") * mouseSensitivity * Time.deltaTime;
  14. mouseY = Input.GetAxis ("Mouse Y") * mouseSensitivity * Time.deltaTime;
  15. xRotation -= mouseY;
  16. xRotation = Mathf.Clamp (xRotation, -70f, 70f);
  17. player.Rotate (Vector3.up * mouseX);
  18. transform.localRotation = Quaternion.Euler (xRotation, 0, 0);
  19. }
  20. }

角色移动

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PlayerController : MonoBehaviour {
  5. private CharacterController cc;//CharacterController
  6. public float moveSpeed;//移动速度
  7. public float jumpSpeed;//跳跃速度
  8. private float horizontalMove, verticalMove;
  9. private Vector3 dir;
  10. public float gravity;//重力
  11. private Vector3 velocity;//速率
  12. public Transform groundCheck;//地面检测
  13. public float checkRadius;
  14. public LayerMask groundLayer;
  15. public bool isGround;
  16. private void Start () {
  17. cc = GetComponent<CharacterController> ();
  18. }
  19. private void Update () {
  20. isGround = Physics.CheckSphere (groundCheck.position, checkRadius, groundLayer);
  21. if (isGround && velocity.y < 0) {
  22. velocity.y = -2f;
  23. }
  24. horizontalMove = Input.GetAxis ("Horizontal") * moveSpeed;//左右移动
  25. verticalMove = Input.GetAxis ("Vertical") * moveSpeed;//前后移动
  26. dir = transform.forward * verticalMove + transform.right * horizontalMove;
  27. cc.Move (dir * Time.deltaTime);
  28. if (Input.GetButtonDown ("Jump") && isGround) {
  29. velocity.y += jumpSpeed;
  30. }
  31. velocity.y -= gravity * Time.deltaTime;
  32. cc.Move (velocity * Time.deltaTime);
  33. }
  34. }