Reputation: 433
I'm trying to animate a jump using 3 variables: Jump distance, jump height and maybe jump "speed".
Here is a working JSFiddle demo. However, I'd like the animated jump to be a perfect parabola.
var y = 300;
var x = 0;
var jh = 100;
var jw = 200;
var c = 0;
var inter = setInterval(function () {
c++;
// if box reaches jump height it should fall down
y = (c >= jh) ? y + 1 : y - 1;
// if box reaches jump distance
if (x == jw) clearInterval(inter);
x++;
$('.box').css({
'top': y + 'px',
'left': x + 'px'
});
}, 20);
Upvotes: 4
Views: 1226
Reputation: 3494
I'm thinking sine? Assuming jh is "Jump height" and jw is "distance" without cleaning up the existing code you could do something like this:
var y = 300;
var x = 0;
var jh = 100;
var jw = 200;
var c = 0;
var speed = 3;
var inter = setInterval(function () {
c++;
y = getHeightAtX(x);
if (x >= jw) clearInterval(inter);
x+=speed;
$('.box').css({
'bottom': y + 'px',
'left': x + 'px'
});
}, 20);
function getHeightAtX(x) {
return jh*Math.sin(x*Math.PI/jw)
};
Upvotes: 2