px is the player's x coordinate in pixels (each object is 16 pixels). py is the player's y coordinate. Object names are stored under d[x][y]. If objects are in the background, d[x][y + "s"] = false. scale is the width and height of objects. The gamescreen is 12 scale high and 16 scale long. The player is in the middle of the screen and is two scale tall and one scale high.
When the code is run, the player should stay above any objects. however, he instead falls through the ground until eventually stopping for an unknown reason. I can move left and right at this point, but moving too far in either direction will cause me to start falling again.
function collision() {
for (gx = 0; gx < 3; gx++) {
for (gy = 0; gy < 4; gy++) {
if (d[Math.floor(px / 16 + 7 + gx)] == undefined) {
d[Math.floor(px / 16 + 7 + gx)] = {};
}
if (d[Math.floor(px / 16 + 7 + gx)][Math.floor(py / 16 + 5 + gy) + "s"] == false && d[Math.floor(px / 16 + 7 + gx)][Math.floor(py / 16 + 5 + gy)] != "none") {
var hit = true;
}
}
}
if (hit == true) {
return true;
} else {
return false;
}
var hit = false;
}
Every time the player tries to move, this code is in an if statement to make sure the player can. This includes gravity pulling players down.
EDIT:
The reason why this isn't working properly is because, for some reason, the collision detection stays in one place in the world instead of moving with the player. This is strange, because px and py work for all other uses, such as moving the world around.