0

I have a game of a rocket landing game, where the player is the rocket and you must land it safely at the right speed on the landing pad. This was taken from www.gametutorial.net

Its actually for educational purposes and I recently added a still meteor in the game. When the player hits the meteor (touches) the game is over.

if(...) {
    playerRocket.crashed = true;
}

My problem is there I need to replace the "..." with the actual condition that "Has the rocket crashed into the meteor?"

Plus the following variables (coordinates, height and width) for use - [All Integers]:

X and Y coordinates: playerRocket.x, playerRocket.y, meteor.x, meteor.y
Height and Width: playerRocket.rocketImgHeight, playerRocket.rocketImgWidth, meteor.meteorImgHeight, meteor.meteorImgWidth
4

2 回答 2

1

对于 2D 游戏中的碰撞检测,您可以使用矩形。我会使用一个名为的基类GObject并从中继承游戏中的所有对象。

public class GObject
{

    private Rectangle bounds;

    public float x, y, hspeed, vspeed;

    private Image image;

    public GObject(Image img, float startx, float starty)
    {
        image = img;
        x = startx;
        y = starty;
        hspeed = vspeed = 0;
        bounds = new Rectangle(x, y, img.getWidth(null), img.getHeight(null));
    }

    public Rectangle getBounds()
    {
        bounds.x = x;
        bounds.y = y;
        return bounds;
    }

}

还有其他方法update()render()但我没有展示它们。因此,要检查两个对象之间的碰撞,请使用

public boolean checkCollision(GObject obj1, GObject obj2)
{
    return obj1.getBounds().intersects(obj2.getBounds());
}

此外,还有一个针对游戏相关问题的特定站点。转到游戏开发堆栈交换

于 2013-06-24T07:18:25.347 回答
1

您需要检查您是否点击了对象,这意味着点击坐标是否在对象的Rectangle.

if( playerRocket.x + playerRocket.width  >= clickX && playerRocket.x <= clickX  &&
    playerRocket.y + playerRocket.height >= clickY && playerRocket.Y <= clickY ) {

    playerRocket.crashed = true;

} 
于 2013-06-24T07:28:47.350 回答