Reputation: 6052
I am working on a little project on JSFiddle just for fun. I was inspired by a simple mario game. I'm just however making a ball move back and forth and jump.
The initial code is working. But what I can't get to happen is a smoother jump. As you can see here, when you hit space (to make the ball jump) and move left, the jump doesn't look like it has real physics. It makes a triangle like jump instead of going smooth in a half circle type motion. My jump code is:
var top = false;
kd.SPACE.up(function () {
var gravity = 0.3;
var jump = setInterval(function () {
cc();
if (top) {
y += yv;
yv -= gravity;
if (y + r > height) {
y = height - r;
clearInterval(jump);
top = false;
}
} else {
y -= yv;
yv += gravity;
if (y < height - 60) {
top = true;
}
}
circle(x, y, r);
}, 1000 / 30);
});
Upvotes: 1
Views: 2454
Reputation: 105015
You can have your mario follow a quadratic curve to present a pleasing jump.
Demo: http://jsfiddle.net/m1erickson/qDQBh/
This function returns an XY along a quadratic curve given a interval-value (T) between 0.00 and 1.00.
T==0 is at the start of the curve.
T==1.00 is at the end of the curve.
function getQuadraticBezierXYatT(startPt,controlPt,endPt,T) {
var x = Math.pow(1-T,2) * startPt.x + 2 * (1-T) * T * controlPt.x + Math.pow(T,2) * endPt.x;
var y = Math.pow(1-T,2) * startPt.y + 2 * (1-T) * T * controlPt.y + Math.pow(T,2) * endPt.y;
return( {x:x,y:y} );
}
Upvotes: 2
Reputation: 249
In general if you want to model realistic "jumping" against the acceleration of gravity, you should be only accelerating from the "jump" in the upward direction initially. This can be modeled by adding a fixed value to your y-velocity at the first frame (when space is pressed). After this point, just subtract your gravity from the y-velocity each frame.
kd.SPACE.up(function () {
var gravity = 0.3;
yv -= 8; // or whatever your jump accel. should be
// you could also just assign this value to yv which is a different effect
var jump = setInterval(function() {
cc();
if (y + r < height) {
y += yv;
yv += gravity;
} else {
y = height - r;
clearInterval(jump);
}
circle(x,y,r);
}, 1000 / 30);
});
Something's weird with this fiddle, or my browser, but here it is I think.
Upvotes: 4