Unity3D中实现人物的第一人称视角
- 打开unity创建一个场景地图可以添加一个Plane作为地面
- 在Hierarchy视图中右键创建一个胶囊体(Capsule)作为Player,添加好后重置胶囊体的位置,并且调整胶囊体在一个合适的位置。
- 将Main Camera拖拽到到player内作为子对象,重置一下Main Camera的transform,并且再调整一下它在player中的位置。大致放在胶囊体的上方位置,像眼睛一样。
- 在project视图中右键创建一个文件夹Scripts用来存放脚本,进入文件夹右键创建一个脚本并且命名为Camrea Controller将创建好的脚本添加到Main Camrea内用来控制相机。
- 打开脚本进行编写
using System.Collections;using System.Collections.Generic;using UnityEngine;public class CameraController : MonoBehaviour{ //获得player的transform public Transform player; //获取鼠标移动的值 private float mouseX, mouseY; //添加鼠标灵敏度 public float mouseSensitivity; //声明变量来累加mouseY public float xRotation; void Update() { //获得鼠标左右移动的值 mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime; //获得鼠标上下移动的值 mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime; xRotation -= mouseY; //用数学函数Mathf.Clamp()将xRotation的值限制在一个范围内 xRotation = Mathf.Clamp(xRotation, -70, 70); //使用transform中的Rotate()方法使player旋转 player.Rotate(Vector3.up * mouseX); //使用transform.localRotation()方法使相机上下旋转 transform.localRotation = Quaternion.Euler(xRotation, 0, 0); }}
6.设置一下脚本的参数
- 再创建一个脚本Player Controller用来控制角色的移动跳跃。
将胶囊体原有的coollder删除添加一个Character Controaller这个组件中包括了碰撞器与刚体组件。
- 编写控制角色的脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;public class PlayerControaller : MonoBehaviour{ //获得Player的CharacterController组件 private CharacterController cc; [Header("移动参数")] //定义player的移动速度 public float moveSpeed; [Header("跳跃参数")] //定义player的跳跃速度 public float jumpSpeed; //定义获得按键值的两个变量 private float horizontalMove, verticalMove; //定义三位变量控制方向 private Vector3 dir; //定义重力变量 public float gravity; //定义y轴的加速度 private Vector3 velocity; //检测点的中心位置 public Transform groundCheck; //检测点的半径 public float checkRadius; //定义需要检测的图层 public LayerMask groundLayer; [Header("检测角色状态")] public bool isOnground; public bool isJump; void Start() { //用GetComponent()方法获得CharacterController cc = GetComponent<CharacterController>(); } void Update() { //使用Physics.CheckSphere()方法改变isOnground的值为true isOnground = Physics.CheckSphere(groundCheck.position,checkRadius,groundLayer); if(isOnground && velocity.y < 0) { velocity.y = -1f; } //用Input.GetAxis()方法获取按键左右移动的值 horizontalMove = Input.GetAxis("Horizontal") * moveSpeed; //用Input.GetAxis()方法获取按键前后移动的值 verticalMove = Input.GetAxis("Vertical") * moveSpeed; //将方向信息存储在dir中 dir = transform.forward * verticalMove + transform.right * horizontalMove; //用CharacterController中的Move()方法移动Player cc.Move(dir * Time.deltaTime); //当键盘按空格的时候可以完成角色的跳跃,并且使角色只能够跳跃一次 if (Input.GetButtonDown("Jump") && isOnground) { velocity.y = jumpSpeed; isJump = true; } //通过每秒减去重力的值不断下降 velocity.y -= gravity * Time.deltaTime; //用CharacterController中的Move()方法移动y轴 cc.Move(velocity * Time.deltaTime); }}
- 在胶囊体下新建一个空物体用来判断角色是否碰到地面图层,并且将位置调整到胶囊体的底部。
- 将地面的图层设置为ground
- 对控制角色移动的脚本添加相应的参数