Search code examples
inputcontrollerunity-game-enginespritedirection

Unity 2d Platformer Controller support


I'm currently trying to create a 2d Platformer in Unity, Everything is working fine except one thing. When I push Left or Right, my sprite animation mirrors to the right direction. I'm currently trying to add controller input, but I cant seem to target pushing the analog left or right. It is supposed to mirror when pushing the stick right and vice versa.

Hope anyone can help me :)

#pragma strict

var X : float;

function Start () {
//Gathering normal object scale
X = transform.localScale.x;
}

function Update () {
    if(Input.GetKey("a")) {
    // Gamer pushes left arrow key
    // Set texture to normal position
    transform.localScale.x = -X;
}
else if (Input.GetKey("d")) {
    // Gamer pushes right arrow key
    // Flip texture
    transform.localScale.x = X;
}
if(Input.GetKey("left")) {
    // Gamer pushes left arrow key
    // Set texture to normal position
    transform.localScale.x = -X;
}
else if (Input.GetKey("right")) {
    // Gamer pushes right arrow key
    // Flip texture
    transform.localScale.x = X;
}
if(Input.GetAxis("Horizontal")) {
    // Gamer pushes left arrow key
    // Set texture to normal position
    transform.localScale.x = -X;
}
else if (Input.GetAxis("Horizontal")) {
    // Gamer pushes right arrow key
    // Flip texture
    transform.localScale.x = X;
    }
}

Solution

  • You have this:

    if(Input.GetAxis("Horizontal")) {
    // Gamer pushes left arrow key
    // Set texture to normal position
    transform.localScale.x = -X;
    }
    else if (Input.GetAxis("Horizontal")) {
    // Gamer pushes right arrow key
    // Flip texture
    transform.localScale.x = X;
    }
    

    The second else if will always be called because you are checking the exact same Input.GetAxis().

    try something like this:

    if (Input.GetAxis("Horizontal") < 0)
    {
        transform.localScale.x = -X;
    }
    else if (Input.GetAxis("Horizontal") > 0)
    {
        transform.localScale.x = X;
    }
    

    Input.GetAxis ("Horizontal") checks all left and right keys that could be pressed and spits out a number depending on either the left or right key...

    Example If I were to press the 'Left Arrow' key, it would return a number between 0 and -1. If I were to press the 'Right Arrow' key, it would return a number between 0 and 1.

    Does this make sense?