First Monkey-X Game: Enemies and Collision

Now that the player can move around the screen, let’s give him some enemies to avoid.

Start by adding a collection to hold our enemy characters.

Now we want to modify the Character class just a little so we can have enemy characters and all of them don’t move when the player touches the controls.

Since we are only going to create 1 player character and we are going to be creating multiple enemies, we are going to give the is_player variable a default of ‘False’ so we can make all our enemies by only passing the first parameter.

Now we need to go and change our player creation code to tell the game that it is a player

Make Some Enemies

Now it is time to make some enemies. We are going to start by making a little generator that creates enemies every 3 seconds or so in our OnUpdate method. We also need to initialize our enemies list.

Now when you run this, you should have some little yellow boxes floating across the middle of the screen every 3 seconds.

Randomize the Enemies

Enemies that always come straight down the middle of the screen every 3 seconds are not that exiting. Let’s spice it up and improve our enemy creator code.

We are going to do 4 things. First we want to randomize where the enemies start. Next we want to randomize how fast they are going. We also want to randomize how often they appear. Finally we want to randomize how big they are and what color they are.

Running into enemies

Now that we have some enemies flying around the screen, lets add some code that checks if we ran into one of them or not.

This adds the checks, but right now we don’t have a way to tell the engine to do anything about them.

What we want to do is extend the engine so we can override its OnObjectCollision method. To do this we are going to create a CustomEngine class that extends Fantom Engine. Create a new custom_engine.monkey file and put in the following code.

One of the ways of passing information back and forth with the engine is by setting Tags and Text on the object. In this case we are going to tell the engine that whenever a PLAYER object and an ENEMY object collided, mark the ENEMY object as DESTROYED and make sure it cannot collide with the PLAYER again.

Now we need to go back and add the text to the player and enemy boxes. Also, in our OnUpdate method, we will remove all the enemies that get destroyed.

Now when you run the game, every time your little character runs into one of the little enemy squares, the enemy should disappear.

Now the Game Truly Begins

With collision working, we can start adding projectiles for our hero to stop the enemies before they even touch his little box.

Tutorial Part 6
Tutorial Part 8

I Want to Be a Better Developer