# C# - Monogame- Collision Detection Sprite walking through platforms

I am blanking on the logic here. How do I get it so that my sprite doesn't run through a block. It only repels if the center of the player sprite is higher than the bottom of the block.

But when it is lower, it walks right through. It gets lower because my jump function or my grounded function is a bit funky. Anyway, how do I get it so that a player can't go underneath a block unless the sprite is not touching the block at all.

Here is the collision code in my player class, the one that does the collision detection.

public void checkYCollisions(block[] platforms)
{

if (position.Y > 700)//this is my ground with no blocks.
grounded = true;
else
grounded = false;

float Xradius = Width / 2;
float Yradius = Height / 2;
block collidedPlatform = null;
List<block> collidedBlocks = new List<block>();

foreach (block p in platforms)
{
if ((position.X > (p.position.X - p.Width / 2 - Xradius )) &&
(position.X < (p.position.X + p.Width / 2 + Xradius )) &&
(position.Y > (p.position.Y - p.Height / 2 - Yradius  )) &&//on top
(position.Y < (p.position.Y + p.Height / 2 + Yradius   )))//below

{

}
}
//collisions work for all side of blocks.
foreach (block p in collidedBlocks)
{
if (p != null)
{
if ((position.Y <
(p.position.Y - p.Height / 2 /*+ radius*/)))//landing on a block
{

grounded = true;

}

else if ((position.Y >
(p.position.Y + p.Height / 2 /*- Yradius*/))) //jumping up into a block
{
if (y_vel < 0)
y_vel *= -1;
//player1.direction.Y = -1.0f * player1.direction.Y;
}

else if ((position.X <
(p.position.X + p.Width / 1.5 /*+ Xradius*/))) // one of the sides
{
x_vel *= -2;
}

else if ((position.X >
(p.position.X - p.Width / 1.5 /*+ Xradius*/))) // other side
{
x_vel *= -2;
}

}
}
}

Note that I have tried to remove YRadius in the the if loops at separate occurences, and it works to no avail because my guy will not hit the ceiling.

• I'll advice you to take a look at Rectangles. They make detecting collisions a lot easier :) – Tyyppi_77 Jul 27 '14 at 16:10

As I suggested in a comment on your other question (and as Tyyppi_77 suggested), you should look into the Rectangle structure. If you utilized it, then your collision code could be as simple as this:

public void checkYCollisions(block[] platforms)
{
// assume player and block both contain a Rectangle property called "Bounds"
// that represent each's bounds

if (this.Bounds.Y + Bounds.Height > 700)
grounded = true;
else
grounded = false;

List<block> collidedBlocks = new List<block>();
foreach (block p in platforms)
{
if (p != null && p.Bounds.Intersects(this.Bounds))
{
}
}

foreach (block p in collidedBlocks)
{
// p won't be null

Rectangle overlap = Rectangle.Intersect(this.Bounds, p.Bounds);

// overlap now contains the amounts (X and Y) by which the player's
// bounds and the block's bounds overlap and you can use that to
// perform your necessary collision responses
}
}