首页 > 解决方案 > 使用 Unity 的新输入系统移动玩家

问题描述

在完成游戏前几天,我刚刚获得了新的统一输入系统包(Big oof),并且我遵循了 Unity Learn 教程,但我似乎无法让它工作。现在,我知道您必须在项目设置和首选项中进行一些额外的配置,我很确定我得到了所有正确的,所以就实际脚本而言,这对你们来说是否正确?

using System.Collections; /*We are using the "using" keyword to signify that we are implementing the Collections class of the System package(because 
unity can not use Generic as a baselayer for a script) in this scope/file*/
using System.Collections.Generic; /*We are using the "using" keyword to signify that we are implementing the Generic class of the System.Collections
package(because it contains generic class definition and provides you to better type safly) in this scope/file*/
using UnityEngine; /*We are using the "using" keyword to signify that we are implementing the UnityEngine class(because it allows us to use all of 
unity class definitions, keywords, default method and everythine) in this scope/file*/
using UnityEngine.InputSystem;

public class PlayerMovementE5 : MonoBehaviour /*Creates a public(which means it's accesible to every other file) with the name 
"PlayerMovementE5" that imports it with the baseclass of "MonoBehaviour"(which means it can be attached to a gameobjct)*/
{

        private Rigidbody player;
        private float movementX;
        private float movementY;
        private float movementZ;
        public float speed = 100;

    void Start() {
        player = GetComponent<Rigidbody>();
    }

    private void OnMove(InputValue movementValue) {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    void FixedUpdate() {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        player.AddForce(movement * speed);
    }
    
}

标签: unity3d

解决方案


unity 的输入系统脚本将包含动作地图上的 Move 和动作上的 MoveLeftRight。MoveLeftRight 的动作类型为直通,控制类型为按钮。然后创建一个 1d 轴类型的新绑定。然后在其下创建另一个属性,然后为其分配所需的键然后保存并关闭输入选项卡,然后转到项目文件夹,然后单击您的输入系统脚本文件并勾选“生成 c# 类”,然后应用。

那么这段代码可能会有所帮助:

void FixedUpdate()
{
    Movement();
}

private void Movement()
{
        speedOfThePlayer = 8;
        float move = playerInput.Move.Move.ReadValue<float>();
        Vector3 positionNow = transform.position;
        positionNow.x += move * speedOfThePlayer;
        transform.position = positionNow;
}

希望对您有所帮助!


推荐阅读