开发者

Java collision detection for rotated rectangles?

I am writing my first java game and so far:

I've made a rectangle that can walk around with WSAD, and he always faces where the mouse is pointing. Also if you click, he shoots bullets where your mouse is pointing (and the bullets rotate to face that direction). I've also made enemies which follow you around, and they rotate to face towards your character. The problem i am having is that the collision detection I've written is only detecting the collision of the objects (character, enemies and bullets) before their rotation (using .intersects()). This means that some parts of their bodies overlap when drawn.

I've been looking around, and I haven't found any solutions that I understand or can apply to my situation. I've been rotating my Graphics2D grid for each of the objects so far, so they are not actually being rotated, just drawn out to be. Is there a way I can actually rotate their shapes and then use something like .intersects() ?

Any help or suggestions are appreciated.

Here is what I use to see if it will collide by moving on 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;
}


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

Assume that you have two objects a and b, you can rotate them like this:

  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
  }

and you have the original objects just in case thats what you want. Using the AffineTransform makes it easy to combine transformations, inverse them etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜