首页 > 解决方案 > 我遵循了有关在统一上为 fps 游戏制作控件的教程。控件可以工作,但是如果我离开控件,那么我会继续向左移动

问题描述

在此处输入图像描述我为我的角色制作了沿 X 轴移动的控件。他们似乎工作正常,但我的角色一直向左移动,我不确定为什么或错过了什么。我已经发布了来自两个单独脚本的代码

我已经多次重新检查他的代码。我检查了我的箭头键、数字键盘键和 WASD 是否粘住或其他任何东西。

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
    private Vector3 velocity = Vector3.zero;

    private Rigidbody rb;

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

    //gets a movement vector
    public void Move (Vector3 _velocity)
    {
        velocity = _velocity;
    }

    //run every physics iteration
    void FixedUpdate()
    {
        PerformMovement();
    }

    //perform movement based on velocity variable
    void PerformMovement ()
    {
        if (velocity != Vector3.zero)
        {
            rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
        }

    }

}

和控制器:

using UnityEngine;

[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
    [SerializeField]                //makes speed show up in inspector even if set to private
    private float speed = 5f;


    private PlayerMotor motor;
    void Start ()
    {
        motor = GetComponent<PlayerMotor>();
    }

    void Update()
    {
        //Calculate movement velocity as a 3D vector
        float _xMov = Input.GetAxisRaw("Horizontal");
        float _zMov = Input.GetAxisRaw("Vertical");

        Vector3 _movHorizontal = transform.right * _xMov;
        Vector3 _movVertical = transform.forward * _zMov;


        //final movement vector
        Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;

        //apply movement
        motor.Move(_velocity);

    }
}

我希望在不按下按钮时输出 0,但它似乎让我以 5 的速度向左移动

标签: c#visual-studiounity3d

解决方案


您连接了一个控制器并报告了一个方向的轻微移动。使用Input.GetAxis而不是Input.GetAxisRaw让 Unity 处理死区检测。这样,几乎中性的输入将被视为中性输入。

void Update()
{
    //Calculate movement velocity as a 3D vector
    float _xMov = Input.GetAxis("Horizontal");
    float _zMov = Input.GetAxis("Vertical");

    Vector3 _movHorizontal = transform.right * _xMov;
    Vector3 _movVertical = transform.forward * _zMov;


    //final movement vector
    Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;

    //apply movement
    motor.Move(_velocity);

}

推荐阅读