Home > Net >  Simple movement system only moves on the X axis (is a problem)
Simple movement system only moves on the X axis (is a problem)

Time:07-09

When using this code on unity (I am very new to coding so please be patient) the character will only move on the X axis. It is just a square that cannot slow down without direct input.

float _walkspeed;
float _inputHorizontal;
float _inputVertical;

// Start is called before the first frame update
void Start()
{
    _rb = gameObject.GetComponent<Rigidbody2D>();

    _walkspeed = 5.5f;
}

// Update is called once per frame
void Update()
{
    _inputHorizontal = Input.GetAxisRaw("Horizontal");

    if (_inputHorizontal != 0)
    {
        _rb.AddForce(new Vector2(_inputHorizontal * _walkspeed, 0f));
    }
}
private void FixedUpdate()
{
    _inputVertical = Input.GetAxisRaw("Vertical");
    if (_inputVertical != 0)
    {
        _rb.AddForce(new Vector2(_inputVertical * _walkspeed, 0f));
    }
}

}

CodePudding user response:

Add vertical force in y-axis in your FixedUpdate() method

private void FixedUpdate()
{
    _inputVertical = Input.GetAxisRaw("Vertical");
    if (_inputVertical != 0)
    {
        _rb.AddForce(new Vector2(0f, _inputVertical * _walkspeed));
    }
}

CodePudding user response:

Do as Geeky Quentin mentioned, and also move your horizontal and vertical input into one function, either FixedUpdate() or Update(). If not, the character will move faster (or possibly slower) on the Y axis.

private void FixedUpdate()
{
    _inputHorizontal = Input.GetAxisRaw("Horizontal");

    if (_inputHorizontal != 0)
    {
        _rb.AddForce(new Vector2(_inputHorizontal * _walkspeed, 0f));
    }

    _inputVertical = Input.GetAxisRaw("Vertical");
    if (_inputVertical != 0)
    {
        _rb.AddForce(new Vector2(_inputVertical * _walkspeed, 0f));
    }
}
  • Related