Setting bounds to a div, via keyboard control
Ok, I have removed my code fro开发者_运维百科m here in favour of uploading the lot here: http://www.project-vanquish.co.cc/jRPGrid-v0.4b/index.html
(please ignore any SQL errors)
- Clicking on a Grid-Node - moves the character to the position (boundries enabled)
- Dragging the character - moves to the position (boundries enabled)
- Using the keyboard cursor keys - moves the character (no boundries).
I would like to set the boundries of the #character to be #map, via keyboard - the boundries work with the mouse
Okay, I suspect the bounding is wrong. I have changed all the if
statements to what I believe is correct to keep the character in the bounds of the map.
$(document).bind('keydown',function(e){ //set the keydown function as...
switch(e.which)
case 37: $(characterName).css("background-image", "url(img/character-left.gif)"); //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)"); //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)"); //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)"); //DOWN ARROW KEY
var character = $(characterName);
var map = $('#map');
if((character.offset().bottom + 40) < map.offset().bottom) {
character.animate(
{
top: '+=40'
},
250,
function(){}
);
}
break;
}
});
I am not the most knowledgeable about JQuery, but my guess is every place that you set top
with something like '+=40'
it probable does not recognize the "+=" as an operator. You should probably set the top
by getting the current value and doing the addition to it then assigning it back to top
.
精彩评论