It seems like the bounding might be off. I've adjusted all the if
statements to ensure that the character stays within the map boundaries.
$(document).bind('keydown',function(e){ //define keydown function...
switch(e.which)
case 37: $(characterName).css("background-image", "url(img/character-left.gif)"); //pressing LEFT ARROW KEY
var character = $(characterName);
var map = $('#map');
if((character.offset().left - 40) > map.offset().left) {
character.animate(
{
left: '-=40'
},
250,
function(){}
);
}
break;
case 39: $(characterName).css("background-image", "url(img/character-right.gif)"); //pressing RIGHT ARROW KEY
var character = $(characterName);
var map = $('#map');
if((character.offset().right + 40) < map.offset().right) {
character.animate(
{
left: '+=40'
},
250,
function(){}
);
}
break;
case 38: $(characterName).css("background-image", "url(img/character-up.gif)"); //pressing UP ARROW KEY
var character = $(characterName);
var map = $('#map');
if((character.offset().top - 40) < map.offset().top) {
character.animate(
{
top: '-=40'
},
250,
function(){}
);
}
break;
case 40: $(characterName).css("background-image", "url(img/character-down.gif)"); //pressing DOWN ARROW KEY
var character = $(characterName);
var map = $('#map');
if((character.offset().bottom + 40) < map.offset().bottom) {
character.animate(
{
top: '+=40'
},
250,
function(){}
);
}
break;
}
});