5

我正在编写我的第一个 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;
}
4

1 回答 1

5

您可能可以使用 AffineTransform 类来旋转各种对象,前提是对象的类型为 Area。

假设您有两个对象 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 可以轻松组合变换、反转它们等。

于 2011-05-08T05:04:48.597 回答