I'm trying to make a little game just for the fun of it where i have some collision problems.
I have a player drawn on a canvas and some blocks (16 x 16px) drawn on another canvas.
But i have a problem with detecting horizontal collisions.
...
My problem comes down to this:
My player uses x y coordinates that are stored as:
var p_x; var p_y;
these values is the players bottom left coordinates in pixels.
But my blocks is in a 2d array called:
var g_levelarray;
And each block is 16 x 16 px so for instance if i do:
g_levelarray[3][2] = 1;
means that a block will be drawn at canvas left: 48px and canvas bottom 32px
...
But then i have my code to check if block exists (according to player) where the x and y is playercoordinates
function blockexists(x, y) {
var xpos = parseInt(x / g_blocksize);
var ypos = parseInt(y / g_blocksize);
$("#checkedblock").html("checked block: " + xpos + " " + ypos);
if (g_levelarray[xpos][ypos] != undefined) {
return true;
}
else {
return false;
}
}
but that check has some errors due to the fact that it rounds down the number so when i hit a block from half down the top (as shown on image below) it allows player to go inside block.

(source: userhome.org)
i have also tried Math.round instead of parseInt but that just makes a problem at players middle.
So how can i write this code in a right way so that my player doesnt go into the block?
thx in advance
Instead of just using the parseInt and round try using a range.
Take the lower bound(Math.floor) and the upper bound Math.ceil and check if the block exists in this range by checking these values in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With