Reputation: 393
I'm creating a game with jQuery, and I want my character to move automatically until it hits a boundary. Here is my movement code in right direction:
if (e.keyCode === 39 && (p1_left < 784)) {
$('#p1').rotate(0);
setInterval ( function() {
$('#p1').animate( { left: "+=16px", }, 50); }, 50);
}
This moves my character indefinetely to the right, and I haven't figured out myself how to create a stopper.
EDIT: Updated code snippet, Added jsfiddle http://jsfiddle.net/BjCeq/
Upvotes: 0
Views: 1687
Reputation: 738
What you need is code that's continually called. Your code, as you've written it, is called once, and it performs all of its DOM manipulation at once. What you need is a setInterval or a setTimeout to trigger your code to call itself a certain number of milliseconds in the future, incrementing the css property each time. The easiest way to accomplish this is to simply use jQuery.animate, which runs those methods internally.
var $p1 = $('#p1');
if (e.keyCode === 39 && (p1_left < 784)) {
$p1.rotate(0);
$p1.animate({ 'left' : 784 });
}
Check out the jQuery animate docs for more information, including how to set options and run a callback function with each frame of the animation: http://api.jquery.com/animate/.
Upvotes: 0
Reputation: 78630
You never actually increase pl_left
so the loop will just run forever:
while (p1_left <= 784) {
pl_left+=16;
$('#p1').css('left', p1_left);
}
However, this is not going to animate the movement of your character, it will appear to just jump to the end point. For this reason it is kind of pointless to loop. What you probably want is either to use setTimeout
to move every second one position or something. Or, you could use animate
with a callback function:
function moveLeft(theID){
$(theIE).animate({...},1000, function(){
if(/* keep moving */){
move_left(theID);
}
}
}
Upvotes: 3