【问题标题】:Java collision detection for rotated rectangles?旋转矩形的Java碰撞检测?
【发布时间】:2011-05-07 11:07:37
【问题描述】:

到目前为止,我正在编写我的第一个 java 游戏:

我制作了一个可以用 WSAD 到处走动的矩形,它总是面向鼠标所指的地方。此外,如果您单击,他会在您的鼠标指向的地方发射子弹(并且子弹会旋转以朝向该方向)。我还制造了跟随你的敌人,它们会旋转以面向你的角色。我遇到的问题是我编写的碰撞检测仅检测对象(角色、敌人和子弹)在旋转之前的碰撞(使用.intersects())。这意味着它们身体的某些部分在绘制时会重叠。

我一直在环顾四周,但没有找到任何我理解或适用于我的情况的解决方案。到目前为止,我一直在为每个对象旋转我的 Graphics2D 网格,所以它们实际上并没有被旋转,只是被绘制出来。有没有办法我可以实际旋转它们的形状,然后使用 .intersects() 之类的东西?

感谢任何帮助或建议。

这是我用来查看它是否会通过在 x 轴上移动来碰撞:

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

【问题讨论】:

  • 你能给出一个简短的代码示例来说明你在做什么吗?
  • @Vincent Ramhanie 我已经编辑了我的帖子。
  • 需要再编辑一下...代码对我来说很难阅读...查看如何在 stackoverflow 上进行 Markdown
  • @WarmWaffles 是的,现在应该看起来好多了,抱歉。

标签: java rotation collision-detection rectangles


【解决方案1】:

如果对象的类型为 Area,您或许可以使用 AffineTransform 类来旋转各种对象。

假设你有两个物体a和b,你可以像这样旋转它们:

  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 可以轻松组合变换、反转它们等。

【讨论】:

  • 哇哦!我会试一试,如果它有效,那就太棒了!那么 a 和 b 是我要旋转的矩形吗?我想我需要将它们变成类型区域。 t
  • 您可以从形状创建区域。因此,如果您的对象是 Shape 类型,您可以使用:Area a = new Area(myshape);
  • 我不能在两个区域使用 .intersects() 显然 =(。我会试着弄清楚...
  • @Dominic 试试 ra.intersects(rb.getBounds()) 。
  • Get bounds 返回一个未旋转但与边界区域一样大的矩形。要检查碰撞,请使用 if(area1.intersects(area2.getBounds()) && area2.intersects(area1.getBounds()))...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2013-04-06
相关资源
最近更新 更多