Java collision detection for rotating rectangles?

I am writing my first Java game and so far:

I made a rectangle that can walk with WSAD, and it always encounters what the mouse points to. Also, if you click, it will fire into the bullets where your mouse pointed (and the bullets rotate in that direction). I also made enemies that followed you, and they turned to face your character. The problem I ran into is that the detected collision only detects the collision of objects (character, enemies and bullets) before they rotate (using .intersects ()). This means that some parts of their bodies overlap when drawing.

I look around and I have not found solutions that I understand or can apply to my situation. For now, I rotate my Graphics2D grid for each of the objects, so they actually do not rotate, but simply stretch. Is there a way I can rotate my shapes and then use something like .intersects ()?

Any help or suggestions are welcome.

Here is what I use to see if it will collide while moving along the x axis:

public boolean detectCollisionX(int id, double xMove, double rectXco, double rectYco, int width, int height)
{
    boolean valid=true;
    //create the shape of the object that is moving.
    Rectangle enemyRectangleX=new Rectangle((int)(rectXco+xMove)-enemySpacing,(int)rectYco-enemySpacing,width+enemySpacing*2,height+enemySpacing*2);
    if (rectXco+xMove<0 || rectXco+xMove>(areaWidth-width))
    {
        valid=false;
    }
    if(enemyNumber>0)
    {
        for (int x=0; x<=enemyNumber; x++)
        {
            if (x!=id)
            {
                //enemies and other collidable objects will be stored in collisionObjects[x] as rectangles.
                if (enemyRectangleX.intersects(collisionObjects[x])==true)
                {
                    valid=false;
                }
            }
        }
    }
    return valid;
}
+5
source share
1 answer

You can probably use the AffineTransform class to rotate various objects if the objects are of type Area.

Suppose you have two objects a and b, you can rotate them as follows:

  AffineTransform af = new AffineTransform();
  af.rotate(Math.PI/4, ax, ay);//rotate 45 degrees around ax, ay

  AffineTransform bf = new AffineTransform();
  bf.rotate(Math.PI/4, bx, by);//rotate 45 degrees around bx, by

  ra = a.createTransformedArea(af);//ra is the rotated a, a is unchanged
  rb = b.createTransformedArea(bf);//rb is the rotated b, b is unchanged

  if(ra.intersects(rb)){
    //true if intersected after rotation
  }

, . AffineTransform , ..

+5

All Articles