1.设置动作类型和控制类型,WSAD键的移动,使玩家在水平面内移动,是一个二维向量。
Jump是一个button
Look是一个值
2.绑定键盘的WSAD
3.绑定鼠标和手柄的方向键,保存所有配置
4.勾选蓝色字体部分
5.点击应用后,会出现一个脚本
6.同时使用新输入系统和旧输入系统会出现错误,导致玩家无法完成跳跃动作。
此时应添加using UnityEngine.InputSystem ,并且删去使用旧输入系统的代码(getAxis)
完整代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControllerWithNewInputAction : MonoBehaviour
{
private CharacterController controller;
[SerializeField] private float moveSpeed = 15f;
[SerializeField] private float mouseSensitivity = 60f;
[SerializeField] private Camera playerEyes;
private float eyesAngleLimit;//眼睛旋转的限制范围
private Vector3 jumpVector;//跳跃向量
[SerializeField] private float jumpHeight = 4f;//可修改
private float gravity = -9.8f;
private bool isOnGround = true;//判断玩家是否在地面上
//图层
[SerializeField] private GameObject groundCheck;
[SerializeField] public LayerMask layerMask;
private MyInputActions inputActions;
private void Start()
{
controller = GetComponent<CharacterController>();//获取组件
inputActions = new MyInputActions();
inputActions.Enable();//激活
}
private void Update()
{
//移动
float horizontalInput = inputActions.Player.Mvoe.ReadValue<Vector2>().x;
float verticalInput = inputActions.Player.Mvoe.ReadValue<Vector2>().y;
Vector3 moveDirection = transform.forward * verticalInput + transform.right * horizontalInput;
controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime );
//normalized保留方向,使长度归一,否则长度也会影响速度
//身体在水平方向旋转
float mouseX = inputActions.Player.Look.ReadValue<Vector2>().x;
transform.Rotate(Vector3.up, mouseX * mouseSensitivity * Time.deltaTime);//省略了this
//眼睛在竖直方向上旋转
float mouseY = inputActions.Player.Look.ReadValue<Vector2>().y;
transform.Rotate(Vector3.up, mouseY * mouseSensitivity * Time.deltaTime);
//以下代码不能合适地控制旋转的角度
//playerEyes.transform.Rotate(Vector3.left, mouseY * mouseSensitivity * Time.deltaTime);
eyesAngleLimit -= mouseY * mouseSensitivity * Time.deltaTime;
eyesAngleLimit = Mathf.Clamp(eyesAngleLimit, -80f, 80f);
playerEyes.transform.localRotation = Quaternion.Euler(eyesAngleLimit, 0, 0);
isOnGround = Physics.CheckSphere(groundCheck.transform.position,0.3f,layerMask);//中心点,半径,检测图层
//if (Input.GetButtonDown("Jump") && isOnGround )
if(inputActions.Player.Jump.triggered && isOnGround )
{
jumpVector.y = jumpHeight;
}
else
{
jumpVector.y += gravity * Time.deltaTime;//模仿有重力的下落
}
controller.Move(jumpVector * Time.deltaTime);//传到Move()方法中才能移动
}
}