Your “bouncingLevel” is commonly called “restitution” and is applied to an object that is colliding.
Restitutions typically range from 0.0 – 1.0.
1.0 means the object is absolutely bouncy—so it loses no speed during a collision.
0.0 means the object loses all it’s speed during a collision—so it “splats” and doesn’t bounce at all.
Here’s how you add restitution to your collision:
Warning: I have not tried my code below…just off the top of my head—you may need to debug!
// create a flag to tell us whether we are currently colliding
var isColliding=false;
// Create a "squash"
// When an object collides, it can get shorter/fatter
// This squash variable simulates the object as it un-squashes
var squash=0;
this.applyGravity = function(gravity, bouncingLevel){
if(isColliding){
// un-squash the object at ySpeed
// note: ySpeed should be negative at this point
squash += this.ySpeed;
// if we're all un-squashed, show the object's motion again
if(squash<0){
// since squash<0 the object will now rise
// above the boundary and start moving upward
this.setY(this.getHeight+squash);
// all done colliding...clear the flag
isColliding=false;
}
return;
}
this.ySpeed += gravity;
this.move(0, this.ySpeed);
if(this.getY() + this.getHeight() > this.bottomBoundary)
{
// set the new after-collision speed
this.ySpeed = -this.ySpeed*bouncingLevel;
// set the collision flag
isColliding=true;
// calculate squash:
// == how far the object's momentum carried it into the boundary
squash = this.getY() + this.getHeight();
// visually set the object on bottomBoundary until it "rebounds"
// alternatively, you could let it visually fall under the boundary
this.setY(this.bottomBoundary - this.getHeight());
this.counter = 0;
}
}