Simple Game Mechanics in Scratch:
Platform Jumping

Because it is fun to jump around.

Continuing in this series of tackks on isolated game mechanics, today I made a simple jump function in Scratch. The code is all commented, but let me break it down a bit more.

The code above actually contains three separate functions: Move Right, Move Left, and Jump. If we exclude the code for Right and Left movement, the necessary components for programming a Jump function are the blue "Change y by 'Yvel'" block and the three "If_Then" condition blocks below it. As the comments explain, each of these statements is a different part of how Jumping works - The first condition check acts as gravity: When the player is not on solid ground, they fall. The second condition check actually stops the player from falling when they touch solid ground. The third condition check is what actually controls the jump when the Up Arrow key is pressed, but it only works when the player is standing on solid ground. This prevents the player from just flying up forever whenever the button is pressed. Of course even though all this code is only within the Player sprite, the jump mechanic depends on having something to act as ground for the player to jump off of.

The Jump Mechanic requires a Terrain object to act as solid ground to land on and jump off of.

The other important element to note is that the code for Jumping requires a custom Variable within the sprite. Variables in Scratch are custom elements that store values and can be plugged into conditions and statements within code. Variables have to be created before they can be used in Scratch and are found in the "Data" block type.

Once created with the "Make a Variable" button, a set of blocks using that variable are available to use within Scratch. This is where I got the "Y-Vel" (Short for Y-Axis Velocity) variable that I use to store data for how far the Player jumps and falls when it is changed by the jump and gravity functions. Try this code out in your own platformer games to make your characters able to jump!