CodexOne03
CodexOne03

Reputation: 3

Input.GetAxisRaw not working properly on Vertical Axis

I'm writing a 2D game and my walking animation won't work on the Vertical axis. I have a script attached to a Player with Rigidbody2D.

I have setup the transitions like this: transition screen link

Here's the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    public Rigidbody2D rb;
    public Animator animator;

    Vector2 movement;

    private void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
        
        if  (movement.y != 0f){
            animator.SetBool("Walking", true);
        }
        if  (movement.y == 0f) {
            animator.SetBool("Walking", false);
        }
        if  (movement.x != 0f){
            animator.SetBool("Walking", true);
        }
        if (movement.x == 0f) {
            animator.SetBool("Walking", false);
        }
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

Upvotes: 0

Views: 1352

Answers (2)

Brian Pajak
Brian Pajak

Reputation: 61

Your code seems to be ok (I set up a new project and copied to test) is it just the animations or the movement in general?

If it's just the animations, I would check your transitions in the animator.

UPDATE: I took a second look and i think this will solve it for you. I think your blocks of if statements are overriding the bool.Replace them with this and you should be good to go.

 if (movement != Vector2.zero){
        animator.SetBool("Walking", true);
    } else{
        animator.SetBool("Walking", false);
    }

Upvotes: 1

bozali
bozali

Reputation: 83

First problem is that you are trying to check if a float number equals 0. Try it with Math.Abs and a precision number. You should never check if a float number "equals" to something.

public static bool AlmostEquals(this double double1, double double2, double precision)
{
     (Math.Abs(double1 - double2) <= precision);
}

But if you want to check if the user is only walking try this code by just using an else statement

if  (AlmostEquals(movement.y, 0.0f, 0.00005)){
    animator.SetBool("Walking", false);
}
else {
    animator.SetBool("Walking", true);
}
if  (AlmostEquals(movement.x, 0.0f, 0.00005)){
    animator.SetBool("Walking", false);
}
else {
    animator.SetBool("Walking", true);
}

If this is not working than check if the transitions are correct like @Brian Pajak said.

Upvotes: 3

Related Questions