I'm making an endless jumper as my first game and I'm running into some problems with the one-way collision detection.
Collisions are detected correctly most of the time but occasionally the player inexplicably falls through the platform.
I suspect that it is ghosting through the platforms but I can't see why and I'm too close to it to be able to identify the source of the problem.
My code:
This loop is located within the update method of the global platforms object. this._platforms refers to the array of Platform objects.
for (i = 0, len = this._platforms.length; i < len; i++) {
var p = this._platforms[i];
p.proximity = Math.abs(p.x / 2 - player.x / 2) + Math.abs(p.y / 2 - player.y / 2);
if (p.closest()) {
if (p.collision()) {
player.onplatform = true;
player.y = p.y - player_s_right.height;
} else {
player.onplatform = false;
}
}
...
}
It loops through the platform objects, running a collision test only if the platform is the closest one to the player.
Here are the closest() and collision() checks respectively:
// Return whether current platform is the closest to the player
Platform.prototype.closest = function() {
var minprox = Math.min.apply(Math, platforms._platforms.map(function (obj) {
return obj.proximity;
}));
return this.proximity === minprox;
}
// Collision detection
Platform.prototype.collision = function() {
var px = player.direction > 0 ? player.x + 15 : player.x,
px2 = player.direction > 0 ? player.x + player_s_right.width : player.x + player_s_right.width - 15,
py = player.y + player_s_left.height,
py2 = player.y + player_s_right.height + player.yvelocity,
platx2 = this.x + platform_s.width,
platy2 = this.y + platform_s.height;
if (((px > this.x && px < platx2) || (px2 > this.x && px2 < platx2)) && (py2 >= this.y && py2 <= platy2) && py <= this.y) {
return true;
}
};
If anyone can shed some light on this I'd really appreciate it.