ESD
ESD

Reputation: 545

collision with rotated rectangle

So basically, I am doing my first xna game and it's an arkanoid game. My ball right now is a square that rotate.

Unfortunately, it's impossible to correctly detect the collision of a rotated rectangle in xna.

I found thing about scalars but I am only in computer science in college so I don't know about these big maths...

Can anyone direct me in the right way to detect these kind of collision ? or at least to be able to obtain a new rectangle in the right way so that I can detect the collision on this one?

EDIT I just thought about making my rotating square in a still square and test the collision with the outer square would that be viable ?

Upvotes: 0

Views: 2027

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

If you want to detect a collision of the square ball with the outer rectangle, you need to know the coordinates of the four corners of the ball. Then simply compare these points with the outer rectangle.

If s is the length of the sides of the rectangle. The corners can be calculated like this:

double h = 0.707106781 * s; // Half diagonal
double angle = rotation_angle + 0.25 * Math.PI; // 0.25 * Math.PI = 45 degrees
                                                // inclination of the diagonal.
double x = h * Math.Cos(angle);
double y = h * Math.Sin(angle);

// The four points are
p1x = +x + squareCenterX;
p1y = +y + squareCenterY;

p2x = -y + squareCenterX;
p2y = +x + squareCenterY;

p3x = -x + squareCenterX;
p3y = -y + squareCenterY;

p4x = +y + squareCenterX;
p4y = -x + squareCenterY;

Upvotes: 1

Msonic
Msonic

Reputation: 1456

Do you really want your ball to be a square? Or a simple circle could do?

You could use a collision circle instead, the logic behind the collision is much more simple than rotated squares... (If you really want a square and a pixel-perfect collision, disregard this answer and see Terrance's comment)

if(circle.Center.X - circle.Radius < ScreenBounds.XMin || 
    circle.Center.X + circle.Radius > ScreenBounds.XMax ||
    circle.Center.Y - circle.Radius < ScreenBounds.YMin || 
    circle.Center.Y + circle.Radius > ScreenBounds.YMax)
{
     //Ball is partly or entirely outside of the screen
}

This is not really a direct answer to your question, but more of an alternative

Edit: This code assumes that the position of your ball is relative to its center.

Also, you can approximate your rotated square's collision with a collision circle (or a non-rotated square as a matter of fact). The collision won't be pixel perfect, but I think that'll be hardly noticeable. It will also be easier to implement (considering this is your first game).

Upvotes: 0

Related Questions