unity玩家第一人称的视角转动和移动 | 您所在的位置:网站首页 › unity3d第一人称控制器 › unity玩家第一人称的视角转动和移动 |
需要一个代表玩家的物体和摄像机,摄像机放在玩家物体的子物体中,玩家物体加上CharacterController组件,该组件已经能实现碰撞(但没有重力),不用额外再加刚体组件。 以下代码分别挂在玩家物体和摄像机上即可实现玩家第一人称的视角转动和移动。 先是玩家的移动代码,挂在玩家物体上: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { private CharacterController cc;//角色控制组件 public float speed = 8; void Start() { cc = this.GetComponent(); } void Update() { Walk(); if (transform.position.y != 1)//保证玩家在地面上,防止卡bug上天 { transform.position = new Vector3(transform.position.x, 1, transform.position.z); } } private void Walk() { float h = Input.GetAxis("Horizontal") * speed * Time.deltaTime;//获取水平移动值 float v = Input.GetAxis("Vertical") * speed * Time.deltaTime;//获取垂直移动值 Vector3 dir = transform.forward * v + transform.right * h;//确定移动的方向 cc.Move(dir);//移动 } }然后控制视角转动的代码,挂在摄像机上: using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { // 水平视角移动的敏感度 public float sensitivityHor = 3f; // 垂直视角移动的敏感度 public float sensitivityVer = 3f; // 视角向上移动的角度范围,该值越小范围越大 public float upVer = -85; // 视角向下移动的角度范围,该值越大范围越大 public float downVer = 85; // 垂直旋转角度 private float rotVer; // 旋转的方向问题 // x 表示绕 x 轴旋转,即 前上后 的角度 // y 表示绕 y 轴旋转,即 左前后 的角度 // y 表示绕 y 轴旋转,即 左前后 的角度 // Start is called before the first frame update void Start() { // 初始化当前的垂直角度 rotVer = transform.eulerAngles.x; } // Update is called once per frame void Update() { // 获取鼠标上下的移动位置 float mouseVer = Input.GetAxis("Mouse Y"); // 获取鼠标左右的移动位置 float mouseHor = Input.GetAxis("Mouse X"); // 鼠标往上移动,视角其实是往下移,所以要想达到视角也往上移的话,就要减去它 rotVer -= mouseVer * sensitivityVer; // 限定上下移动的视角范围,即垂直方向不能360度旋转 rotVer = Mathf.Clamp(rotVer, upVer, downVer); // 设置视角的移动值 transform.localEulerAngles = new Vector3(rotVer, 0, 0);//控制摄像机的上下视角移动(玩家不动) transform.parent.Rotate(Vector3.up * mouseHor);//转动玩家的水平视角移动(摄像机也会动) } } |
CopyRight 2018-2019 实验室设备网 版权所有 |