Search code examples
gmlgame-maker-studio-2

sprite_index not working gamemaker studio 2 (GML)


I have a small script that changes the sprite index when I press a certain key.

 if (key_right)
    {
    sprite_index = playerRightSpr;//<-------------
    image_speed = 1;                           //|
    }                                          //|
    if (key_left)                              //|
    {                                          //|
    sprite_index = playerLeftSpr;              //|
    image_speed = 1;                           //|
    }                                          //|
    if (key_left) && (key_right)               //|
    {                                          //|
    sprite_index = playerSpr;                  //|
    image_speed = 0;                           //|
    }                                          //|
    if (!key_right or key_left) //add this and this, doesn't work
    {                           //but it does when I remove this code.
    sprite_index = playerSpr;
    image_speed = 0;
    }

Is there another way to say when standing still make sprite playerSpr because the way i'm trying seems to cause conflict. Thanks in advance Bhodi


Solution

  • If your entity moves you can just use the speed variable to make this. For example :

    • if your entity has a positive speed (go right) you will use PlayerRightSpr

    • if your entity has a negative speed (go left) you will use PlayerLeftSpr

    • And if speed is 0 you use PlayerSpr

    (Instead of using two different sprites you can use image_xscale too)

    image_xscale = 1; (normal sprite)
    
    image_xscale = -1; (flip on x axis : mirror)
    

    And finally instead of this :

    if (!key_right or key_left)
    

    Use this :

    if (!key_right || !key_left)

    Or this :

    if (key_right == 0 || key_left == 0)
    

    But you are right it's not the correct way to do this

    I hope this way is good