1 /* 2 这是一个第一人称移动脚本 3 */ 4 using UnityEngine; 5 using System.Collections; 6 using System; 7 8 public class Player : MonoBehaviour { 9 //位置记录 10 public Transform m_transform; 11 12 //角色控制器组件 13 CharacterController m_ch; 14 //角色移动速度 15 public float m_movSpeed = 3.0f; 16 //重力 17 float m_gravity = 2.0f; 18 //生命值 19 public int m_life = 5; 20 21 //摄像机位置控制 22 public Transform m_camTransform; 23 //摄像机旋转角度 24 Vector3 m_camRot; 25 //摄像机高度 26 public float m_camHeight = 1.4f; 27 28 void Start() 29 { 30 m_transform = this.transform; 31 //获取角色控制器 32 m_ch = this.GetComponent<CharacterController>(); 33 34 //初始化摄像机 35 //获取摄像机 36 m_camTransform = Camera.main.transform; 37 //设置摄像机初始位置 38 Vector3 pos = m_transform.position; 39 pos.y += m_camHeight; 40 m_camTransform.position = pos; 41 //摄像机的旋转方向与主 角方向一样 42 m_camTransform.rotation = m_transform.rotation; 43 m_camRot = m_camTransform.eulerAngles; 44 //锁定鼠标 45 Screen.lockCursor = true; 46 } 47 void Update() 48 { 49 if (m_life <= 0) 50 return; 51 Control(); 52 } 53 54 void Control() 55 { 56 //三个值控制移动 57 float ym = 0, xm = 0, zm = 0; 58 //重力运动 59 ym -= Time.deltaTime * m_gravity; 60 //控制移动 61 //向前移动 62 if (Input.GetKey(KeyCode.W)) 63 { zm += Time.deltaTime * m_movSpeed; } 64 //向后 65 else if (Input.GetKey(KeyCode.S)) 66 { zm -= Time.deltaTime * m_movSpeed; } 67 68 //向左 69 if (Input.GetKey(KeyCode.A)) 70 { xm -= Time.deltaTime * m_movSpeed; } 71 else if (Input.GetKey(KeyCode.D)) 72 { xm += Time.deltaTime * m_movSpeed; } 73 //使用CharacterControl的Move函数进行移动,它会自动检测碰撞 74 m_ch.Move(m_transform.TransformDirection(new Vector3(xm, ym, zm))); 75 76 77 //获取鼠标移动距离 78 float rh = Input.GetAxis("Mouse X"); 79 float rv = Input.GetAxis("Mouse Y"); 80 81 //旋转摄像机 82 m_camRot.x -= rv; 83 m_camRot.y += rh; 84 m_camTransform.eulerAngles = m_camRot; 85 86 //主角面向方向与摄像机一致 87 Vector3 camrot = m_camTransform.eulerAngles; 88 camrot.x = 0; 89 camrot.z = 0; 90 m_transform.eulerAngles = camrot; 91 92 //使摄像机位置与主角一样 93 Vector3 pos = m_transform.position; 94 pos.y += m_camHeight; 95 m_camTransform.position = pos; 96 } 97 }