Josh-CO Dev

Solving the worlds problems one line of code at a time.

XNA – Simple Collision Detection

Leave a comment


Here is some incredibly simple code to check for collisions. The method is accepting an x and a y coordinate. The for loop then loops through each object on the screen and checks first to see if the x value is within the x-range of the object. If that check returns true, it performs the same check against the y-range. If all checks are true, we remove the object from the list so it will no longer be drawn and increase the score.

public void checkClick(int xPos, int yPos)
{
//iterate through the balls
for (int ball = 0; ball < balls.Count; ball++)
{
//check the x position first
if ((xPos >= balls[ball].Position.X) && (xPos <= (balls[ball].Position.X +  balls[ball].Texture.Width)))
{
//cehck the y position
if ((yPos >= balls[ball].Position.Y) && (yPos <= (balls[ball].Position.Y + balls[ball].Texture.Height)))
{
balls.RemoveAt(ball);
ballCount–;
score++;
}
}
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s