using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControllerWithCode : 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 InputAction moveAction;
private InputAction jumpAction;
//private InputAction lookAction;
private void Start()
{
controller = GetComponent<CharacterController>();//获取组件
moveAction = new InputAction("Move", binding:"<Gamepad>/LeftStick") ;//绑定游戏手柄的左摇杆
moveAction.AddCompositeBinding("Dpad")//组合绑定
.With ("Up","<keyboard>/w")
.With("Up", "<keyboard>/upArrow")
.With("Down", "<keyboard>/s")
.With("Down", "<keyboard>/dowmArrow")
.With("Left", "<keyboard>/a")
.With("Left", "<keyboard>/leftArrow")
.With("Right", "<keyboard>/d")
.With("Right", "<keyboard>/rightArrow");
moveAction.Enable();
//lookAction = new InputAction("Look");
jumpAction = new InputAction("Jump",binding :"<Gamepad >/a");
jumpAction.AddBinding("<keyboard>/space");
jumpAction.Enable();
}
private void Update()
{
//移动
float horizontalInput = moveAction .ReadValue<Vector2>().x;
float verticalInput = moveAction .ReadValue<Vector2>().y;
Vector3 moveDirection = transform.forward * verticalInput + transform.right * horizontalInput;
controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime );
//normalized保留方向,使长度归一,否则长度也会影响速度
// //身体在水平方向旋转
float mouseX = Mouse.current.delta.ReadValue().x;
transform.Rotate(Vector3.up, mouseX * mouseSensitivity * Time.deltaTime);//省略了this
// //眼睛在竖直方向上旋转
float mouseY = Mouse.current.delta.ReadValue().y;
//transform.Rotate(Vector3.up, 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 (jumpAction .triggered && isOnGround)
{
jumpVector.y = jumpHeight;
}
else
{
jumpVector.y += gravity * Time.deltaTime;//模仿有重力的下落
}
controller.Move(jumpVector * Time.deltaTime);//传到Move()方法中才能移动
}
}
08-22
411
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-21
1270
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-23
198
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-21
287
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)