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:
- Responding to the user's button press to jump
- Falling back down to the ground under gravity
- 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
The Final Code
You can download the final code here: 2D_character2.c
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...