I'm trying to make a little fun spaceshooter game. I animated the position of my spaceship, but when I press up or down, it jumps to the top of the parent element. I've noticed that it overwrites the css "bottom"-property when doing so. Does someone know how to fix this?
Here's my code:
$(document).keydown(function(key) {
switch(parseInt(key.which)) {
case up:
$('#ship').animate({top: "-=100px"}, '10', 'linear');
break;
case down:
$('#ship').animate({top: "+=100px"}, '10', 'linear');
break;
case left:
$('#ship').animate({left: "-=100px"}, '10', 'linear');
break;
case right:
$('#ship').animate({left: "+=100px"}, '10', 'linear');
break;
}
});
You must specify top
or bottom
, but not both as only one can be active at a time. If you had a bottom
value and then you set a top
value, you will not get a smooth movement from where it was because it will animate from the default value of top
which is 0
to your 100px
less than that which will cause it to immediately jump to top:0
and then animate from there.
If you are going to initially specify bottom
and want to animate smoothly from that, then animate the bottom
value, not the top
value.
So, either change your initial CSS to use top
instead of bottom
or change your code to animate bottom
. Be consistent between the two and you won't see the jump when you animate.