1
\$\begingroup\$

I have 2 objects, A and B, both are classes with only values, so positions and dimensions are only values (float posX,posY).

I have a render class which render A and B with shapeRenderer; A is rendered as a rectangle and B as a circle, how could check if there is a collision ?

edit: I have a rectangle coming from up, when it hits the circle I have to stop the game

enter image description here

\$\endgroup\$
0
\$\begingroup\$

This is what I use to check collision between circle / rectangle. Note that this doesn't do continuous collision detection. Which means that if both of the shapes are unproportionally small or the objects are colliding with really high speeds (because you have too low fps and you use Delta Time to calculate the velocity for example), then the collision won't be detected.

static public Boolean CircleRectCollision(Vector2 circleCenter, Vector2 rectCenter, 
    float radius, float width, float height)
{
    float distanceY = Math.Abs(circleCenter.Y - rectCenter.Y);
    if (distanceY > (height / 2 + radius)) return false;

    float distanceX = Math.Abs(circleCenter.X - rectCenter.X);
    if (distanceX > (width / 2 + radius)) return false;

    if (distanceX <= (width / 2)) return true;
    if (distanceY <= (height / 2)) return true;

    float a = distanceX - width / 2;
    float b = distanceY - height / 2;
    float cSqr = a * a + b * b;
    return (cSqr <= (radius * radius));
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ My objects are moving. Could Intersector help? \$\endgroup\$ – user65825 May 14 '15 at 22:20
  • \$\begingroup\$ ContantListener does continuous collision detection if bodies are bullets. This question is also helpful for how to check collisions in Box2D libgdx. However, you still haven't described how your game looks like. I would assume you probably don't need a whole physics library for just a collision. Make sure that you need continuous collision before you use that library. \$\endgroup\$ – dimitris93 May 14 '15 at 22:35
  • \$\begingroup\$ I am going to edit my question \$\endgroup\$ – user65825 May 14 '15 at 22:37
  • \$\begingroup\$ @user65825 That image doesn't really explain a lot. Because I don't know how many pixels that is and how fast the objects are moving. Just try and see if it works for you. Try use a bit higher speed than usual to test it. Your objects need to be really small or move really fast for my function to not identify the collision. \$\endgroup\$ – dimitris93 May 14 '15 at 22:42
  • \$\begingroup\$ Your code works, I only changed one thing because I had to adapt to my game. Thank you so much! Marked as best answer. \$\endgroup\$ – user65825 May 15 '15 at 0:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.