I showed my wife the first RayLib challenge, and the first words out of her mouth were, "can he jump?" Uh, no. Scarfy can't jump. So, today I'm going to give scarfy the ability to jump, and add some sound effects for added realism. Watch the video above to see how it was done.

Making Scarfy Jump

Making a character jump requires three things:

  1. Responding to the user's button press to jump
  2. Falling back down to the ground under gravity
  3. The fall needs to stop when he/she hits the ground (i.e., collision detection)

Each part is relatively simple. Checking the jump button is just like checking for left and right button presses, with the added restriction that button presses should only work when scarfy is on the ground (humans can't change direction mid-jump). Gravity, is a simple acceleration constant that gets added to an object's velocity every frame. And, for collision detection I cheated: the ground was a vertical y-position that is measured from the top of the screen. This won't work for a platform game, but is good enough for the challenge.

Adding Sound Effects

Sound effects are pretty easy in RayLib. A quick look at the audio section in RayLib's cheat sheet show a few key functions:

  • InitAudioDevice() - call at the start of the program to initialize audio
  • CloseAudioDevice() - call at the end of the program to shut down the audio
  • LoadSound() - loads sound samples in the most common formats
  • PlaySound() - plays a sound sample

I downloaded two footstep samples from Fesliyan Studios (here). One for scarfy's footsteps, and the other for the sound when scarfy lands after jumping.

The Final Code

You can download the final code here: 2D_character2.c

NOTE: You'll also need the scarfy bitmap from RayLib's examples/textures/resources/ directory, and sound samples from Fesliyan Studios (here). Or, you could create your own data files.

The code has become rather complicated. It would be a great idea to add some structure to the code before it gets too complicated. That, however, is going to have to wait till another time...

Click here for part 3 of the RayLib 2D Challenge.