문제

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
도움이 되었습니까?

해결책

For collision detection in 2D games, you can use rectangles. I'd use a base class called GObject and inherit all objects in the game from it.

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

}

There's also other methods like update() and render() but I'm not showing them. So to check for collision between two objects use

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

Also, there's a specific site for game related questions. Go to Game Development Stack Exchange

다른 팁

You need to check if you hit the object, meaning, if the click coordinates are within the object's Rectangle.

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

    playerRocket.crashed = true;

} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top