1. Game Development
  2. Programming

Make a Neon Vector Shooter for iOS: More Gameplay

Read Time:20 minsLanguages:
This post is part of a series called Cross-Platform Vector Shooter: iOS.
Make a Neon Vector Shooter for iOS: First Steps

In this series of tutorials, I'll show you how to make a Geometry Wars-inspired twin-stick shooter, with neon graphics, crazy particle effects, and awesome music, for iOS using C++ and OpenGL ES 2.0. So far, we've set up the basic gameplay; now, we'll add enemies and a scoring system.


In this part we will build upon the previous tutorial by adding enemies, collision detection, and scoring.

Here are the new features in action:

We will add the following new classes to handle this:

  • Enemy
  • EnemySpawner: Responsible for creating enemies and gradually increasing the game's difficulty.
  • PlayerStatus: Tracks the player's score, high score, and lives.

You may have noticed that there are two types of enemies in the video, but there's only one Enemy class. We could derive subclasses from Enemy for each enemy type. The original XNA version of the game didn't, because of the following drawbacks:

  • They add more boilerplate code.
  • They can increase the complexity of the code and make it harder to understand. The state and functionality of an object becomes spread out over its entire inheritance chain.
  • They aren't very flexible—you can't share pieces of functionality between different branches of the inheritance tree if that functionality isn't in the base class. For example, consider making two classes, Mammal and Bird, which both derive from Animal. The Bird class has a Fly() method. Then you decide to add a Bat class that derives from Mammal and can also fly. To share this functionality using only inheritance you would have to move the Fly() method to the Animal class where it doesn't belong. In addition, you can't remove methods from derived classes, so if you made a Penguin class that derived from Bird, it would also have to have a Fly() method.

For this tutorial, we will side with the original XNA version and favor composition over inheritance for implementing the different types of enemies. We will do this by creating various reusable behaviors that we can add to enemies. We can then easily mix and match behaviors when we create new types of enemies. For example, if we already had a FollowPlayer behavior and a DodgeBullet behavior, we could make a new enemy that does both simply by adding both behaviors.


Enemies will have a few additional properties over entities. In order to give the player some time to react, we'll make enemies gradually fade in before they become active and dangerous.

Let's code the basic structure of the Enemy class:

This code will make enemies fade in for 60 frames and will allow their velocity to function. Multiplying the velocity by 0.8 fakes a friction-like effect. If we make enemies accelerate at a constant rate, this friction will cause them to smoothly approach a maximum speed. The simplicity and smoothness of this type of friction is nice, but you may want to use a different formula depending on the effect you want.

The wasShot() method will be called when the enemy gets shot. We'll add more to it later in the series.

We want different types of enemies to behave differently; we'll accomplish this by assigning behaviors. A behavior will use some custom function that runs each frame to control the enemy.

The original XNA version of Shape Blaster used a special language feature from C# to automate the behaviors. Without going into too much detail (since we won't be using them), the end result was that the C# runtime would call the behavior methods every frame without having to explicitly say so.

Since this language feature doesn't exist in either C or C++, we'll will have to explicitly call the behaviors ourselves. Though this requires a little more code, the side benefit is we'll know exactly when our behaviors are updated and thus gives us finer control.

Our simplest behavior will be the followPlayer() behavior shown below:

This simply makes the enemy accelerate towards the player at a constant rate. The friction we added earlier will ensure it eventually tops out at some max speed (five pixels per frame when acceleration is one unit, since \(0.8 \times 5 + 1 = 5\).

Let's add the scaffolding needed to make behaviors work. Enemies need to store their behaviors, so we'll add a variable to the Enemy class:

mBehaviors is a std::list containing all active behaviors. Each frame we'll go through all the behaviors the enemy has and call the behavior function based on the behavior type. If the behavior method returns false, it means that the behavior has completed, so we should remove it from the list.

We'll add the following methods to the Enemy class:

And we'll modify the update() method to call ApplyBehaviours():

Now we can make a static method to create seeking enemies. All we have to do is pick the image we want and add the followPlayer() behavior:

To make an enemy that moves randomly, we'll have it choose a direction and then make small random adjustments to that direction. However, if we adjust the direction every frame, the movement will be jittery, so we'll only adjust the direction periodically. If the enemy runs into the edge of the screen, we'll have it choose a new random direction that points away from the wall.

We can now make a factory method for creating wandering enemies, much like we did for the seeker:

Collision Detection

For collision detection, we'll model the player's ship, the enemies, and the bullets as circles. Circular collision detection is nice because it's simple, it's fast, and it doesn't change when the objects rotate. If you recall, the Entity class has a radius and a position (the position refers to the center of the entity)—this is all we need for circular collision detection.

Testing each entity against all other entities that could potentially collide can be very slow if you have a large number of entities. There are many techniques you can use to speed up broad phase collision detection, like quadtrees, sweep and prune, and BSP trees. However, for now, we will only have a few dozen entities on screen at a time, so we won't worry about these more complex techniques. We can always add them later if we need them.

In Shape Blaster, not every entity can collide with every other type of entity. Bullets and the player's ship can collide only with enemies. Enemies can also collide with other enemies; this will prevent them from overlapping.

To deal with these different types of collisions, we will add two new lists to the EntityManager to keep track of bullets and enemies. Whenever we add an entity to the EntityManager, we'll want to add it to the appropriate list, so we'll make a private addEntity() method to do so. We'll also be sure to remove any expired entities from all the lists each frame.

Replace the calls to entity.add() in EntityManager.add() and EntityManager.update() with calls to addEntity().

Now let's add a method that will determine whether two entities are colliding:

To determine whether two circles overlap, simply check whether the distance between them is less than the sum of their radii. Our method optimizes this slightly by checking if the square of the distance is less than the square of the sum of the radii. Remember that it's a bit faster to compute the distance squared than the actual distance.

Different things will happen depending on which two objects collide. If two enemies collide, we want them to push each other away; if a bullet hits an enemy, the bullet and the enemy should both be destroyed; if the player touches an enemy, the player should die and the level should reset.

We'll add a handleCollision() method to the Enemy class to handle collisions between enemies:

This method will push the current enemy away from the other enemy. The closer they are, the harder it will be pushed, because the magnitude of (d / d.LengthSquared()) is just one over the distance.

Respawning the Player

Next, we need a method to handle the player's ship getting killed. When this happens, the player's ship will disappear for a short time before respawning.

We start by adding two new members to PlayerShip:

At the very beginning of PlayerShip::update(), add the following:

And we override draw() as shown:

Finally, we add a kill() method to PlayerShip:

Now that all the pieces are in place, we'll add a method to the EntityManager that goes through all the entities and checks for collisions:

Call this method from update() immediately after setting mIsUpdating to true.

Enemy Spawner

The last thing to do is make the EnemySpawner class, which is responsible for creating enemies. We want the game to start off easy and get harder, so the EnemySpawner will create enemies at an increasing rate as time progresses. When the player dies, we'll reset the EnemySpawner to its initial difficulty.

Each frame, there is a one in mInverseSpawnChance of generating each type of enemy. The chance of spawning an enemy gradually increases until it reaches a maximum of one in twenty. Enemies are always created at least 250 pixels away from the player.

Be careful about the while loop in GetSpawnPosition(). It will work efficiently as long as the area in which enemies can spawn is bigger than the area where they can't spawn. However, if you make the forbidden area too large, you will get an infinite loop.

Call EnemySpawner::update() from GameRoot::onRedrawView() and call EnemySpawner::reset() when the player is killed.

Score and Lives

  • In Shape Blaster, you begin with four lives, and will gain an additional life every 2,000 points.
  • You receive points for destroying enemies, with different types of enemies being worth different amounts of points.
  • Each enemy destroyed also increases your score multiplier by one.
  • If you don't kill any enemies within a short amount of time, your multiplier will be reset.
  • The total amount of points received from each enemy you destroy is the number of points the enemy is worth, multiplied by your current multiplier.
  • If you lose all your lives, the game is over and you start a new game with your score reset to zero.

To handle all this, we will make a static class called PlayerStatus:

Call PlayerStatus::update() from GameRoot::onRedrawView() when the game is not paused.

Next, we want to display your score, lives, and multiplier on screen. To do this we'll need to add a tSpriteFont in the Content project and a corresponding variable in the Art class, which we will name Font. Load the font in Art's constructor as we did with the textures.


Note: The font we're using is actually an image rather than something like a TrueType font file. Image-based fonts were how classic arcade games and consoles printed text on screen, and even now some current generation games still use the technique. One benefit we gain from this is that we'll end up using the same techniques to draw text on screen as we do other sprites.

Modify the end of GameRoot::onRedrawView() where the cursor is drawn, as shown below:

DrawRightAlignedString() is a helper method for drawing text aligned on the right side of the screen. Add it to GameRoot by adding the code below:

Now your lives, score, and multiplier should display on screen. However, we still need to modify these values in response to game events. Add a property called mPointValue to the Enemy class.

Set the point value for different enemies to something you feel is appropriate. I've made the wandering enemies worth one point, and the seeking enemies worth two points.

Next, add the following two lines to Enemy::wasShot() to increase the player's score and multiplier:

Call PlayerStatus::removeLife() in PlayerShip::kill(). If the player loses all their lives, call PlayerStatus::reset() to reset their score and lives at the start of a new game.

High Scores

Let's add the ability for the game to track your best score. We want this score to persist across plays so we'll save it to a file. We'll keep it really simple and save the high score as a single plain-text number in a file (this will be in the App's "Application Support" directory, which is a fancy name for the "preferences" directory.)

Add the following to PlayerStatus:

CreatePathIfNonExistant2() is a function I've made that will create a directory on the iOS device if it doesn't already exist. Since our preference path will not exist initially, we'll have to create it the first time.

GetExecutableName2() returns the name of the executable. We'll use the name of the application as part of the preference path. We'll use this function instead of hard-coding the name of the executable, so that we can just re-use this code for other applications unchanged.

GetPreferencePath2() returns the full string version name of the preference path, and creates the path if it doesn't already exist.

The LoadHighScore() method first checks that the high score file exists, and then returns what's in the file as an integer. It's unlikely that the score will be invalid unless as the user is generally unable to change files manually from within iOS, but if it the score ends up being a non-number, the score will just end up being zero.

We want to load the high score when the game starts up, and save it when the player gets a new high score. We'll modify the static constructor and reset() methods in PlayerStatus to do so. We'll also add a helper member, mIsGameOver, which we'll use in a moment.

That takes care of tracking the high score. Now we need to display it. We'll add the following code to GameRoot::onRedrawView() in the same SpriteBatch block where the other text is drawn:

This will make it display your score and high score on game over, centered in the screen.

As a final adjustment, we'll increase the time before the ship respawns on game over to give the player time to see their score. Modify PlayerShip::kill() by setting the respawn time to 300 frames (five seconds) if the player is out of lives.

The game is now ready to play. It may not look like much, but it has all the basic mechanics implemented. In future tutorials we will add particle effects and a background grid to spice it up. But right now, let's quickly add some sound and music to make it more interesting.

Sound and Music

Playing sound and music is fairly simple in iOS. First, let's add our sound effects and music to the content pipeline.

First, we make a static helper class for the sounds. Note that the game's Sound Management class is called Sound, but our Utility library's sound class is called tSound.

Since we have multiple variations of each sound, the Explosion, Shot, and Spawn properties will pick a sound at random among the variants.

Call Sound's constructor in GameRoot::onInitView(). To play the music, add the following line at the end of GameRoot::onInitView().

To play sounds in, you can simply call the play() method on a SoundEffect. This method also provides an overload that allows you to start the sound after a certain duration of time, and adjust the number of times the sound loops. We'll use -1 for the music as that is equivalent to "looping forever."

To trigger the sound effect for shooting, add the following line in PlayerShip::update(), inside the if statement where the bullets are created:

Likewise, trigger an explosion sound effect each time an enemy is destroyed by adding the following to Enemy::wasShot():

You now have sound and music in your game. Easy, isn't it?


That wraps up the basic gameplay mechanics. In the next tutorial, we'll add a virtual gamepad on-screen so that we can move and shoot at the same time.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.