Continuing from last week, in this article I’ll be walking through some basic collision. Again, I’ll be starting with the code base from last week, so you can go and grab that over at my SkyDrive share.
To get started, we’ll need something to collide with. I’ve created some enemies for use with the game, which you can download from SkyDrive. I’ll start with Enemy-6.png, the one that looks like this:
To do this, add it into the TriangleShooterContent project by right-clicking the project in the Solution Explorer and choosing Add –> Existing Item, and selecting Enemy-6.png. We’ll then need to create a variable to hold the texture, and a variable to track it’s position. In a later article, we’ll add some basic AI to control it, but for now, it will be static.
We’ll also need to add a line to the Draw method to display the enemy.
If we run the application, we now can see that there is an enemy with which we can collide.
But how can we tell if the collision has happened? How about we change the color of the triangle to red? To do this, we’ll have to add a variable to track the color, and set it to red when the collision happens.
Now we’re ready for the collision. We’ll take care of it in the Update method. To check for collision, we have a few options. The easiest would be either rectangle intersection or testing a rectangle to see if it contains a point. In this case, I’ll be using the Rectangle.Contains. The Contains method takes a Point, while our position is a Vector2, so we’ll have to do a bit of casting. We’ll also have to construct a rectangle from the position and texture we have in order to find out if it contains the point. The lines that need to be added into the Update method are as follows:
And now, when we run the application and run into the enemy, we get the following:
Next week, we’ll break everything out into classes, and maybe even add some AI to the enemies.
Download the latest version of the source code,