0
votes

I am using Slick and Tiled2D to make a top-down RPG style game. I am trying to do collision, but the player seems to be able to go through blocks that are on the left side of a building, or the left half of a block. The full project is here: http://github.com/Cj1m/RPG Here is my code for the player movement and collision detection:

@Override
public void update(GameContainer gc, int delta) throws SlickException {
    input = gc.getInput();
        if(input.isKeyDown(Input.KEY_W)){
            if(!isBlocked(x, y - delta * 0.1f)){
                y-=0.1 * delta;
                timer(0,1,delta);
            }
        }else if(input.isKeyDown(Input.KEY_S) && y < screenBottomEdge){
            if (!isBlocked(x, y + playerHeight + delta * 0.1f)){
                y+=0.1 * delta;
                timer(0,0,delta);
            }
        }else if(input.isKeyDown(Input.KEY_A) && x > screenLeftEdge){
            if (!isBlocked(x - delta * 0.1f, y)){
                x-=0.1 * delta;
                timer(0,2,delta);
            }
        }else if(input.isKeyDown(Input.KEY_D) && x < screenRightEdge){
            if (!isBlocked(x + playerWidth + delta * 0.1f, y)){
                x+=0.1 * delta;
                timer(0,3,delta);
            }
        }
}

and

private boolean isBlocked(float x, float y) {
    int xBlock = (int)x / 30;
    int yBlock = (int)y / 30;
    return blocked[xBlock][yBlock];
}
1
The statements using (int) _ / 30 are probably returning 0 since you are dividing by an integer.sdasdadas
In isBlocked, you are casting too soon. Try float xBlock = x/30; (same for yBlock), then in the return, try return blocked[(int) xBlock][(int) yBlock];Samich

1 Answers

0
votes

I guess the x and y in isBlocked are the player's pixel-accurate x and y-positions, while xBlock and yBlock are the tile-accurate positions.

When you say they go through half of the block this seems to me like a rounding-problem at

int xBlock = (int)x / 30;
int yBlock = (int)y / 30;

Try something along the lines of

(int) Math.round(x/30.0);