Exercises for Week 4 - Physics
If you're absolutely sure your game is not going to use any physics (e.g. you're writing a card game) then you can skip these exercises and focus on your game engine instead.
1. Projectiles - Take some existing code (either one of the sample code files, or something you've been working on already) and add a "shoot" button.
Make it so that when the player hits a key, the player character launches a projectile (bullet, arrow, laser, cross-shaped boomering, etc.). Each projectile should move on its own until it collides with something else or until it goes off the screen.
The easiest thing is to make projectiles that move in straight lines forever (i.e. they are not affected by gravity or any other forces) but projectiles that go in arcs (give them an initial upward velocity and let them be affected by gravity) are pretty fun too, as are projectiles that bounce off of surfaces.
You'll need a constructor for projectile objects. Each object will need a position and velocity, and your update loop will need to update the positions of each projectile according to their velocity.
You'll need an array to store all of the projectile objects on the screen. When the player fires, create a new projectile and add it to the array; when the projectile hits something or goes off screen, remove it from the array. Many games impose a limit on the maximum number of player projectiles allowed to be on the screen at one time (e.g. Mega Man can only have three arm cannon bullets on the screen at once, did you ever notice?). Up to you if you want to do something like that.
2. Wind - take your code from part 1 and add wind. This is a sideways force that should affect all moving objects - from jumping players to flying projectiles. If you pay attention to the demo code for the gravity example, it should be easy to figure out how to add an additional sideways force.
The difference is that while gravity accelerates all objects at the same rate, the wind should affect lighter objects more than heavier objects. That means you'll need to give objects a mass property.
For more fun, make the wind vary in strength and direction as time passes!