Try putting this in your player class:

public boolean intersects(Tile tile) {
tile = this.tile;
Rectangle r1 = new Rectangle(x, y, width, height);
Rectangle r2 = tile.getRectangle();
if(r1.intersects(r2) || r2.intersects(r1)) {
return true;
} else {
return false;
}

And in your main class, put:

if(player.intersects(tile) {
System.out.println("Intersects!");
}

To get a visual interpretation of the rectangles, put this code in your method where you render:
CDetection
// This is at the top of the class
public boolean meshMode;
// Rendering:
public void render(Graphics2D g) {
player.render(g);
tile.render(g);
if(meshMode) {
// You can of course use any color
g.setColor(Color.GREEN);
// If your ints/doubles aren't public, then make some getters.
g.drawRect(player.x, player.y, player.width, player.height);
g.drawRect(tile.x, tile.y, tile.width, tile.height);
// In Key Listeners:
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
if(k == KeyEvent.VK_M) {
meshMode = true;
}
if(k == KeyEvent.VK_N) {
meshMode = false;
}
}
}
}

This is a very simple way to calculate collision detection in a 2D Java Game.
Hope this helps a lot :)

Tags: , ,


One Response to “For those having trouble with collision detection in Java:”

  1. g_o says:

    I’m pretty sure there’s a built in intersection box. I think though you need to make sure it’s axis aligned

Leave a Reply

You must be logged in to post a comment.

[cache: storing page]