Your first game! Part 3: Collisions

Posted on: March 26, 2015 at 7:27 pm,

Colliding!

So our asteroids fly around the screen but are completely none interactive. Asteroids is a fairly simple game, whereby every time there is some sort of collision, something gets destroyed. The logic we’re going to construct is as follows:

Bullet collides with asteroid: Asteroid and bullet are both destroyed.

Player collides with asteroid: Game restarts.

Both of these are incredibly easy to set up and we can do them both from the asteroid object itself. Open up obj_asteroid and add a “collision” event for obj_bullet.

http://puu.sh/gQDQZ/5262d7c40a.png

as you might imagine, this event is triggered when a collision occurs between obj_asteroid and obj_bullet. GameMaker detects a collision when the collision masks of the two sprites overlap at any point in the game.

All we want to happen in this situation is for this particular asteroid instance, and the specific bullet instance that hit it, to both be destroyed. We can do this with instance_destroy actions by simply dragging in two of them. One of them applying to “other” and the other applying to “self”:

destroy2

The keyword “other” refers to the specific other instance an object collided with during a collide event.

Alternatively we can accomplish this same task through two “execute code” actions that run “instance_destroy”. When you create an execute code action, the code editor has the same “applies to” selection available at the top and can also be referred to in the code itself using constructs like “with (other)” (More on that another time.) Allowing you to do more complex things using these keywords.

The second collision event is even simpler. Add another collision event but this time for obj_player. Once you’ve done this simply find the “game restart” action in “main2” tab:

http://puu.sh/gQF27/a97253ce08.png

and add it to the event! Now when the player collides with an asteroid the game will restart instantly. It’s not super pretty or great feeling, but it’s functional and something we can improve upon as the series goes on.

And there you have it, that’s the basics of making collisions work. We will look at fine tuning these collisions in a later part as for now our default collision masks will be less than ideal, but next up in part 4 we will be looking at parent & child objects and splitting up asteroids into smaller chunks when they’re destroyed.

I hope you’re finding this series useful so far!

Pages: 1 2 3