I am making a 2D Java game and i’m trying to figure out how to add basic “gravity”
my current code is this:
public void checkCollision() {
Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);
for(Wall wall : walls) {
Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);
if(player_rectangle.intersects(wall_rectangle)) {
player.yspeed = 0;
} else {
player.yspeed = 1;
}
}
For some reason my code just goes straight through the walls even if it is touching it. I want it to hit the wall if one is present beneath it and if there isnt then keep falling.
you’re iterating over all your walls. If the wall intersected is not the last wall in the list, subsequent walls may reset your speed to 1. Break your loop when you detect intersection. Specifically: