First of all sorry for my terrible English, isn´t my native language.
I´m trying to do a little RPG game with a character walking across a map (old rpg style, like zelda or pokemon maybe).
You can see my code here: jsFiddle URL
i´m a bit stuck, cause when my two layers collide, I can´t find a way to stop my .animate in the direction of the other layer, but allow it to move in other directions. For example:
If #character goes to the right and collide with the other layer(#stone01, the black one), i want to stop moving to the the right but allow to move up, down and left.
Here you can see my Javascript code to detect my two elements collide:
function collision($yo, $obstaculo) {
var x1 = $yo.offset().left;
var y1 = $yo.offset().top;
var h1 = $yo.outerHeight(true);
var w1 = $yo.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $obstaculo.offset().left;
var y2 = $obstaculo.offset().top;
var h2 = $obstaculo.outerHeight(true);
var w2 = $obstaculo.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
Hope anyone can give me any tip about it, THANKS!
What I would do is get the position of the #stone and the position of the character and check to see when they are the same if they are the same I would return false and set a flag canMoveRight to false.
I assume that a keydown event handler would be used and the distance would be 1px and first I check if the layers overlap and proceed accordingly
var canMoveRight = true;
$("#character")
.on(
{
keydown : function()
{
if(checkLayerOverlap())
$("#character").stop();
else
move(1);
return false;
}
}
);
function move(distance)
{
$("#character").animate({
right : "+=" + distance + "px"
},"slow");
}
function checkLayerOverlap()
{
var isOverLapping = false;
var characterPosition = $("#character").position();
var stonePosition = $("#stone").position();
if(characterPosition.right == stonePosition.right)
{
canMoveRight = false;
isOverLapping = true;
}
return isOverLapping;
}
of course all that logic should be expressed in objects so your $("#character") would be
var Character = {
canMoveRight = true,
move : function(distance)
{
//code here
}
}
this is just a hint :)