So I’m trying to make collision work in my platformer. I have a player entity, and a collision component that I’m adding to the entity. Here’s the update function in the collision component:
@Override
public void update(GameContainer gc, StateBasedGame sb, int delta) {
Vector2f position = owner.getPosition();
position.x += owner.getVelocity().x;
rect.setLocation(position);
for (int i = 0; i < map.getWidth(); i++) {
for (int j = 0; j < map.getHeight(); j++) {
if (map.getTileId(i, j, 0) > 0) {
Rectangle tileRect = new Rectangle(i*16, j*16, 16, 16);
if (rect.intersects(tileRect)) {
if (owner.getVelocity().x < 0) {
position.x = tileRect.getX()+tileRect.getWidth();
}
if (owner.getVelocity().x > 0) {
position.x = tileRect.getX()-rect.getWidth();
}
rect.setLocation(position);
}
}
}
}
position.y += owner.getVelocity().y;
rect.setLocation(position);
for (int i = 0; i < map.getWidth(); i++) {
for (int j = 0; j < map.getHeight(); j++) {
if (map.getTileId(i, j, 0) > 0) {
Rectangle tileRect = new Rectangle(i*16, j*16, 16, 16);
if (rect.intersects(tileRect)) {
if (owner.getVelocity().y < 0) {
position.y = tileRect.getY()+tileRect.getHeight();
}
if (owner.getVelocity().y > 0) {
position.y = tileRect.getY()-rect.getHeight();
}
rect.setLocation(position);
}
}
}
}
owner.setPosition(position);
}
If you’re having trouble understanding what the code does, here’s some pseudo code:
-Move the player's Rectangle across the x axis according to the players x velocity
-Check to see if the player's Rectangle collides with any of the tiles' rectangles
-if it does:
-if the player is going left:
-set the player's x position to be just right of the tile
-if the player is going right:
-set the player's x position to be just left of the tile
-Move the player's Rectangle across the x axis according to the player's y velocity
-Check to see if the player's Rectangle collides with any of the tiles' rectangles
-if it does:
-if the player is going up:
-set the player's y position to be just below the tile
-if the player is going down:
-set the player's y position to be just above the tile
This works well until I start moving the player across the x-axis. When the player moves right or left, suddenly the player is shot to the edge of the very left tile in the row. Anyone know how to fix this?