简体   繁体   中英

Pacman collision detection using a matrix

I have a 2 dimensional array called board , that is 32x32. Every element is 0 for clear path or -1 for wall.

The window resolution is 800x800, meaning every element of board has width and height of 25.

My pacman position is in screen coordinates. I'm trying to implement the next two functions to basically know if I can move Pacman to some position (in screen coordinates).

public static boolean canMove(Pair<Integer> pacmanPos, int[][] board) {
    Pair<Integer> boardPos = pacmanPosToBoardPos(pacmanPos);

    int j = boardPos.getX();
    int i = boardPos.getY();

    return board[i][j] != -1;
}

public static Pair<Integer> pacmanPosToBoardPos(Pair<Integer> pacmanPos) {
    int x = pacmanPos.getX();
    int y = pacmanPos.getY();

    int newX = (int)Math.round((double)(x+12.5) / 25.0) % 32;
    int newY = (int)Math.round((double)(y+12.5) / 25.0) % 32;

    return new Pair<Integer>(newX, newY);
}

This was my best shot. I added 12.5 to x and y to refer to the "center" of the some element of board , if that makes sense.

Obviously this does not work and Pacman runs into walls :( . Any idea?

If you want the following mapping:

co-ordinates     board pos

0-24             0
25-49            1
50-74            2
etc

then just use integer division

int newX = (x / 25) % 32;
int newY = (y / 25) % 32;

If you want to actually perform collision, and your Pacman has a width and height, you need to offset the co-ordinates from the center of the Pacman when you test. For example, if you are moving right and your Pacman is 25 pixels wide, then add 12.5 to the x co-ordinate that you want to test (and subtract if you are moving left etc). To avoid using non-integers, you can put your "centerpoint" in the top left of the Pacman, and add 25 when moving right or down, and 0 with moving left or up.

If you want to separate the rendering from the model, do the above calculations in "game units" or whatever unit you store the Pacman's position in rather than pixels, and then apply a transformation to screen co-ordinates when you render. However, you do need to have some mapping between grid indices and these game units (even if that just means storing positions as grid indices with a fractional part and throwing it away when you want the index), because collisions (eg with ghosts) do not necessarily occur at grid cell boundaries. Of course, if you want "pixel perfect" collision, then the mapping between the units you do collision in and the rendering units can be 1:1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM