Friday, September 15, 2017

javascript - Collision between free player and tilebased map


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?




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...