Java Game Development- Sprites colliding?

146 views Asked by At

This is my first question so excuse me if I break any rules or something.

I have been developing a Mario game and I am working on drawing sprites. I am trying to nail collision detection. With research, i learned that you could use the Rectangle class to do this so...

 public void checkCollisions() {
    Rectangle mr = mario.getBounds();
    Rectangle gr = goomba.getBounds();
    if(mr.intersects(gr)) {
        System.out.println("Collision detected");
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    updateMario();
    checkCollisions();
    repaint();
}

However this spams the collision method even when mario is half a screen away from the other sprite!

So the overall question is, how do i get the system not to spam the message when the sprites are away from each other?

Classes: http://pastebin.com/PHWTzSvQ

I used the Zetcode game resource by the way.

1

There are 1 answers

0
Thomas Koon On

I solved it.

Instead of the intersect method i used a method that turned the sprite location into a string:

public String getLocationAsString() {
    return x+" "+y;
}

And then i used this

 public void checkCollisions() {
    if(mario.getLocationAsString().equalsIgnoreCase(goomba.getLocationAsString())) {
        System.out.println("Collision");
    }
}

Thanks for the help! (Also yay for first question)