I added collision to my game but I have a problem. But first I´ll give you some background.
I have this:
// Function that verifies if a point is inside a rectangle
// point {x,y}
// rectangle {x,y,w,h}
function contains(point, rectangle) {
return point.x > rectangle.x &&
ponto.x < rectangle.x + rectangle.w &&
ponto.y > rectangle.y &&
ponto.y < rectangle.y + rectangle.h;
}
On update(); function
I have this:
//Save player´s position
var xOld = xPlayer;
var yOld = yPlayer;
That is used here:
// Detect collision with obstacles
for(var i in obstacles1) {
var rPlayer = {x:xPlayer, y:yPlayer, w:wPlayer, h:hPlayer};
if( contains({x:xPlayer, y:yPlayer}, obstacles1[i]) ||
contains({x:xPlayer+wPlayer, y:yPlayer}, obstacles1[i]) ||
contains({x:xPlayer, y:yPlayer+hPlayer}, obstacles1[i]) ||
contains({x:xPlayer+wPlayer, y:yPlayer+hPlayer}, obstacles1[i]) ||
contains({x:obstacles1[i].x, y:obstacles1[i].y}, rPlayer) ||
contains({x:obstacles1[i].x+obstacles1[i].w, y:obstacles1[i].y}, rPlayer) ||
contains({x:obstacles1[i].x, y:obstacles1[i].y+obstacles1[i].h}, rPlayer) ||
contains({x:obstacles1[i].x+obstacles1[i].w, y:obstacles1[i].y+obstacles1[i].h}, rPlayer) ){
xPlayer = xOld;
yPlayer = yOld;
}
}
Note:
wPlayer and hPlayer are the width and height of the player, as the animation is done through a spritesheet.
xPlayer and yPlayer are the positions of the Player
This makes the player stop when going against an obstacle (kind of). With my code the player will constantly be running against that same obstacle (by getting teleported to its old positions) until the input stops.
The problem with this code is that when I´m pressing more than one key and the player is going into an obstacle he´ll get stuck on the wall even though he is performing another animation.
Is there a way to make him "slide" across the obstacles? I can´t think of anything...
Sorry for this big post and sorry if I didn´t explain myself well. If you have any questions I´ll be happy to make it clearer.
pontoshould bepointme thinks. - Blindman67