GML Sprite walk animation not working?

C

chimericalCharlatan

Guest
I'm relatively new to GML, so bear with me. I'm coding my player's movement/animation etc etc but the problem is, while the player moves and switches to the correct sprite according to the key pressed, the sprite doesn't actually animate. I know I'm doing something wrong but I'm not sure what. Here's my code:

Code:
if keyboard_check(vk_left) x -= 2
if keyboard_check(vk_right) x += 2
if keyboard_check(vk_up) y -= 2
if keyboard_check(vk_down) y += 2

if keyboard_check_pressed(vk_left)
    sprite_index = spr_player_l
    global.moving = true
if keyboard_check_pressed(vk_right)
    sprite_index = spr_player_r
    global.moving = true
if keyboard_check_pressed(vk_up)
    sprite_index = spr_player_b
    global.moving = true
if keyboard_check_pressed(vk_down)
    sprite_index = spr_player_f
    global.moving = true
   
if keyboard_check_released(vk_left)
    global.moving = false
if keyboard_check_released(vk_right)
    global.moving = false
if keyboard_check_released(vk_up)
    global.moving = false
if keyboard_check_released(vk_down)
    global.moving = false

if global.moving = true
    image_speed = 0.2

if global.moving = false
    image_index = 0
    image_speed = 0
 

Perseus

Not Medusa
Forum Staff
Moderator
You need to use curly brackets to group actions together if there's more than one action that is to be executed when a condition is met. The if statement will only dictate whether the first of the following actions is executed or not. So, for instance, in your code, if global.moving = false controls only the image_index assignment, and the assignment which sets image_speed to 0 is always executed regardless of whether the aforementioned condition is met or not. Since image_speed winds up being reset to 0 every step, the spite doesn't animate. The same thing applies to the rest of your if statements.

Here's how I'll write that bit of code:
Code:
if (global.moving) {
    image_speed = 0.2;
} else {
    image_index = 0;
    image_speed = 0;
}
 
N

nickvm98

Guest
When I was new at GML I did the style of coding you did i.e if key_right {move_right} and so on. This is an inefficient method of movement but there are also many ways to code movement whether you use Axes, vector based movement or just jump to position player.x+speed. Depending on what game you want to use the right one. If your game is like a Zelda RPG, use Axes I can give you my code, or if it is a vector based shooter, I'll send you a link to an article. A rule of thumb is don't repeat lines of code and to keep your sprites and movement code separate.
 
Top