In post 2 we gave our players basic movement options, going left, right and jumping. This post we'll add ducking to this list. I'm putting ducking in a separate post because making the players duck is a tad different compared to the other basic movements. Mind you, its quite easy.
SPRITE INDEX
When player1 ducks, we want him to be half the size of his original sprite. To do this we create a new sprite exactly the way we created the other sprites (See Post 1) except this time, when we are in the image editor, we make sure that we fill only the bottom half of the sprite (the sprite is 16x32, fill the bottom 16x16). Be sure you use the same color as before.
Now you have a second sprite which is half the size of the original sprite. Give the sprite a easy to remember name in line with the naming convention you used for the other sprites. My original sprite is called spr_char. My ducking sprite is called spr_char_low.
What we want is that player1 switches to the new sprite whenever he ducks. We do this with sprite_index. But first we'll use the following code learned in our previous post, assigning a key and checking if player1 is standing on a tile. Choose whichever key you want to use. I'll use the down arrow. We follow this with sprite_index which we assign to our newly made sprite. We do this in our player1's Step Event, in the same place where we wrote our previous movement code.
if keyboard_check(vk_down) && !(place_free(x,y+1))
{
sprite_index = spr_char_low;
}
else
{
sprite_index = spr_char;
}
Now you can duck and the place_free check ensures we can only duck when standing on a tile (not while jumping/falling etc). If we try this code out we see that we can still move around while ducking. To fix this we edit our movement code.
if (keyboard_check(vk_right) && place_free(x+walk_speed,y)) && sprite_index = spr_char
{
x += walk_speed;
}
Now we have included a check in the movement code which checks if the sprite of the player is the normal sprite meaning he can't move around if he's ducking because then he uses another sprite.
ASSIGNMENT: MAKE PLAYER2 DUCK
Do the same you did for player1 to player2 to get a hang of it. Also build in the sprite check for movement to the left and jumping.
Take a look at how I did it (including assignment answers) here.