0
\$\begingroup\$

so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely.

Now, i have a problem with collision detection/response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff.

Basic info:

  • The player is the same size as the tiles
  • The tiles are 8x8
  • The map is stored in an array like this: [0, 0, 0, 1, 1, 1, 0, 0, 0]. So if the map was 3x3 there would be a horizontal line in the center.

I feel that the system that I'm using is very inefficient and there are some problems with it:

sides = {};

// The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying.
// The player.y * mapWidth + player.x thing gets the tile at that position in the map array
// I use Math.floor instead of round to get the tile to the left of the player
if (map[(Math.round(player.y / 8) * mapWidth) + Math.floor(player.x / 8)] == 1) {
    sides.left = true;
} else {
    sides.left = false;
}

if (sides.left) {
    // Set the players x position to exactly outside the wall.
    player.x = Math.floor((player.x / 8) - 1) * 8;
}

Now this works fine for walls but when you use it on the ground it works but it glitches on corners.

For example if the player half way over an edge it falls through the tile and is pushed to the side.

Is there a better way to do this and if not, how do i fix the ground collision?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You are falling through the corners because you are comparing the left side of the object to the left side of the player (or middle if that is where x is), you need to compare to the right side of the player as well to make sure you don't fall through the corner (make sure the side of the object is between the right and left side of the player).

\$\endgroup\$
1
  • \$\begingroup\$ Well, if i do that i get pushed up to the top when i walk into the side of the wall. \$\endgroup\$
    – user79268
    Commented Feb 18, 2016 at 14:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .