Unity解决:3D开发模式第三人称视角 WASD控制角色移动旋转 使用InputSystem

Unity版本:2019.2.3f1

目录

安装InputSystem

[1:创建InputHander.cs脚本 挂载到Player物体上 获取键盘输入WADS](#1:创建InputHander.cs脚本 挂载到Player物体上 获取键盘输入WADS)

2.创建PlayerLocomotion.cs挂载到Player物体上,控制物体移动转向


安装InputSystem

菜单栏/Window/Package Manager/Input System

工程面板内 右键-->创建Input Actions

选中New Controls改名为PlayerControls 然后属性 面板按下Edit asset

Action Maps添加:PlayerMovement

Actions添加:New action 改名为MovementAction

Properties项 修改ActionType=Pass Through

修改ControlType= Vector2

在MovementAction项点击+号 选择Add 2D Vector Composite

生成WASD

绑定Up、Down、Left、Right,如此类推

回到PlayerControls属性面板 勾选Generate C# Class[*]

工程面板就生成了一份 PlayerControls.cs 脚本,先不管它

然后创建2个脚本挂到Player物体上

1:创建InputHander.cs脚本 挂载到Player物体上 获取键盘输入WADS

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputHander : MonoBehaviour
{

    public float horizontal;
    public float vertical;
    public float moveAmount;
    public float mouseX;
    public float mouseY;

    PlayerControls inputActions;//声明 InputSystem的脚本对象
    Vector2 movementInput;//存储 WASD输入的值

    public void OnEnable()
    {
        //获取设备上的输入
        if (inputActions == null)
        {
            inputActions = new PlayerControls();
            //绑定输入的值
            inputActions.PlayerMovement.MovementAction.performed += outputActions => movementInput = outputActions.ReadValue<Vector2>();
        }

        inputActions.Enable();//启用
    }

    public void OnDisable()
    {
        inputActions.Disable();//禁用
    }


    public void TickInputt(float delta)
    {
        MoveInput(delta);
    }

    public void MoveInput(float delta) {

        horizontal = movementInput.x;
        vertical = movementInput.y;
        moveAmount = Mathf.Clamp01(Mathf.Abs(horizontal) + Mathf.Abs(vertical));
    }

}

2.创建PlayerLocomotion.cs挂载到Player物体上,控制物体移动转向

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerLocomotion : MonoBehaviour
{

    InputHander inputHander;
    Vector3 moveDirection;

    public CapsuleCollider capsuleCollider;
    public new Rigidbody rigidbody;
    Vector2 movementInput;//存储 WASD输入的值
    Transform cameraObject;

    [HideInInspector]
    public Transform myTransform;

    [Header("Stats")]
    [SerializeField]
    float movementSpeed = 5;
    [SerializeField]
    float rotationSpeed = 10;



    // Start is called before the first frame update
    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
        if (rigidbody==null)
        {
            rigidbody = gameObject.AddComponent<Rigidbody>();
            rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
            
        }
        capsuleCollider = GetComponent<CapsuleCollider>();
        if (capsuleCollider==null)
        {
            capsuleCollider = gameObject.AddComponent<CapsuleCollider>();
            capsuleCollider.center = new Vector3(0, 1, 0);
            capsuleCollider.radius = 0.5f;
            capsuleCollider.height = 2;
            capsuleCollider.direction = 1;
        }
       
        inputHander = GetComponent<InputHander>();
        cameraObject = Camera.main.transform;
        myTransform = transform;
    }

    // Update is called once per frame
    void Update()
    {
        float delta = Time.deltaTime;
        inputHander.TickInputt(delta);

        moveDirection = cameraObject.forward * inputHander.vertical;
        moveDirection += cameraObject.right * inputHander.horizontal;
        moveDirection.Normalize();

        float speed = movementSpeed;
        moveDirection *= speed;

        //移动
        Vector3 projectedVelocity = Vector3.ProjectOnPlane(moveDirection, new Vector3(0, 0, 0));
        rigidbody.velocity = projectedVelocity;

        HandleRotation(delta);
    }

    //转向
    private void HandleRotation(float delta) {

        Vector3 targerDir = Vector3.zero;

        targerDir = cameraObject.forward * inputHander.vertical;
        targerDir += cameraObject.right * inputHander.horizontal;

        targerDir.Normalize();
        targerDir.y = 0;

        if (targerDir == Vector3.zero)
        {
            targerDir = myTransform.forward;
        }

        Quaternion tr = Quaternion.LookRotation(targerDir);
        Quaternion targetRotation = Quaternion.Slerp(myTransform.rotation, tr, rotationSpeed * delta);

        myTransform.rotation = targetRotation;
    
    }
}

完成

相关推荐
Artistation Game17 小时前
九、怪物行为逻辑
游戏·unity·游戏引擎
百里香酚兰17 小时前
【AI学习笔记】基于Unity+DeepSeek开发的一些BUG记录&解决方案
人工智能·学习·unity·大模型·deepseek
妙为17 小时前
unreal engine5制作动作类游戏时,我们使用刀剑等武器攻击怪物或敌方单位时,发现攻击特效、伤害等没有触发
游戏·游戏引擎·虚幻·碰撞预设
dangoxiba20 小时前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
先生沉默先2 天前
使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志
学习·unity·贴图
十画_8242 天前
Visual Studio 小技巧记录
unity·visual studio
red_redemption2 天前
cpp,git,unity学习
git·unity·游戏引擎
tealcwu2 天前
【Unity踩坑】Unity更新Google Play结算库
unity·游戏引擎
先生沉默先2 天前
unity 默认渲染管线材质球的材质通道,材质球的材质通道
unity·游戏引擎·材质
白鹭float.2 天前
【Unity AI】基于 WebSocket 和 讯飞星火大模型
人工智能·websocket·unity