Java collision detection for rotated rectangles?

≯℡__Kan透↙ 提交于 2019-12-10 14:12:59

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/5920638/java-collision-detection-for-rotated-rectangles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!