Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From \$16.50/m

# Projectile Physics Engines: Building a Game World

Difficulty:IntermediateLength:MediumLanguages:

In What's in a Projectile Physics Engine, we covered the theory and essential elements of physics engines that can be used to simulate projectile effects in games like Angry Birds. Now, we'll cement that knowledge with a real example. In this tutorial, I'll break down the code for a simple physics-based game that I've written, so you can see exactly how it works.

For those interested, the example code provided throughout this tutorial uses the Sprite Kit API provided for native iOS games. This API uses an Objective-C wrapped Box2D as the physics simulation engine, but the concepts and their application can be used in any 2D physics engine or world.

## Building a Game World

Here is the sample game in action:

The overall concept of the game takes the following form:

1. A structure of platforms with physics bodies are added to the level, building a tower.
2. One or more objective objects are placed within the tower, each with a physics body assigned to it.
3. A firing mechanism shoots a projectile body with an momentary impulse; when the projectile's body collides with the platforms' bodies, the simulation takes over and computes the results for us.
4. If a projectile or a platform touches the objective, it fades from the scene, and the player wins! This collision is detected using the physics bodies, so that the simulation maintains its realism at the point of collision.

Our first use of physics will be to create an edge loop body around our screen's frame. The following is added to an initializer or `-(void)loadLevel` method:

This will keep all of our objects within the frame, so that gravity won't pull our whole game off the screen!

Let's look at adding some physics-enabled sprites to our scene. First, we will look at the code for adding three types of platforms. We will use square, rectangular, and triangular platforms to work with in this simulation.

We'll get to what all the property declarations mean in a bit. For now, focus on the creation of each body. The square and the rectangular platforms each create their bodies in a one line declaration, using the sprite's bounding box as the body size. The triangle platform's body requires drawing a path; this also uses the sprite's bounding box, but calculates a triangle at the corners and halfway points of the frame.

The objective object, a star, is similarly created, but we will use a circular physics body.

The cannon itself doesn't need any bodies attached, as it has no need for collision detection. We will simply use it as a starting point for our projectile.

Here is the method for creating a projectile:

Here we see a more complete declaration of some properties assignable to a physics body. When playing with the sample project later, try altering the `restitution`, `friction`, and `density` of the projectile to see what effects they have on the overall gameplay. (You can find definitions for each property in What's in a Projectile Physics Engine?)

The next step is to create the code to actually shoot this ball at the target. For this, we'll apply an impulse to a projectile based on a touch event:

Another fun alteration to the project might be to play with the impulse vector value. Forces—and therefore impulses—are applied using vectors, giving magnitude and direction to any force value.

Now we have our structure and our objective, and we can shoot at them, but how do we see if we scored a hit?

## Collision Course

First, a quick pair of definitions:

• A contact is used when two bodies touch.
• A collision is used to prevent two bodies from intersecting.

### Contact Listener

So far, the physics engine has been handling contacts and collisions for us. What if we wanted to do something special when two particular objects touch? To start with, we need to tell our game that we want to listen for the contact. We will use a delegate and a declaration to accomplish this.

We add the following code to the top of the file:

...and add this statement to the initializer:

`self.physicsWorld.contactDelegate = self`

This allows us to use the method stub depicted below to listen for contact:

Before we can use this method, though, we need to discuss categories.

### Categories

We can assign categories to our various physics bodies, as a property, to sort them into groups.

Sprite Kit in particular uses bit-wise categories, meaning we are limited to 32 categories in any given scene. I like to define my categories using a static constant declaration like this:

Note the use of bit-wise operators in the declaration (a discussion on bitwise operators and bit variables is beyond the scope of this tutorial; just know that they are essentially just numbers stored in a very quickly accessed variable, and that you can have 32 maximum).

We assign the categories using the following properties:

Doing the same for the other variables in the project, let's us now complete our contact listener method stub from earlier, and also this discussion!

## Conclusion

I hope that you've enjoyed this tutorial! We have learned all about 2D physics and how they can be applied to a 2D projectile game. I hope you now have a better understanding of what you can do to start using physics in your own games, and how physics can lead to some new and fun gameplay. Let me know in the comments below what you think, and if you use anything you've learned here today to create projects of your own, I'd love to hear about it.

### A Note on the Example Project

I have included a working example of the code provided in this project as a GitHub repo. The fully commented source code is there for all to use.

Some minor portions of the working project unrelated to physics were not discussed in this tutorial. For instance, the project is built to be expandable, so the code allows the loading of multiple levels using a property list file to create different platform arrangements and multiple objectives to hit. The game over section, and the code to remove objects and timers, were also not discussed, but are fully commented and available within the project files.

Some ideas for features you could add to expand on the project:

1. Different types of ammo
2. Movable and scalable shot direction and magnitude
3. More types and sizes of platforms
4. Terrain
5. Animation and sound effects