Reputation: 25
I created a simple Ball
prototype, which includes a draw()
and a move()
function. The ball should bounce on floor, walls and ceiling. For some reason however, it doesn't stop bouncing, although the velocity (vy
) get's decreased continiously... Do you know what I did wrong?
function Ball(radius,x,y,vx,vy,color){
this.radius = radius;
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.color = color;
this.gravity = 0.6;
this.friction = {
air: 0.005,
bounce: 0.3
};
}
Ball.prototype.move = function(){
this.x += this.vx;
this.y += this.vy;
//Gravity
this.vy += this.gravity;
//Air Friction
this.vx /= 1+this.friction.air;
this.vy /= 1+this.friction.air;
//Bounce Border
if(this.x<this.radius){//Left
this.x = this.radius+((this.radius-this.x)/(1+this.friction.bounce));
this.vx /= -(1+this.friction.bounce);
}
if(this.x>width-this.radius){//Right
this.x = (width-this.radius)-((this.x-(width-this.radius))/(1+this.friction.bounce));
this.vx /= -(1+this.friction.bounce);
}
if(this.y<this.radius){//Top
this.y = this.radius+((this.radius-this.y)/(1+this.friction.bounce));
this.vy /= -(1+this.friction.bounce);
}
if(this.y>height-this.radius){//Bottom
this.y = (height-this.radius)-((this.y-(height-this.radius))/(1+this.friction.bounce));
this.vy /= -(1+this.friction.bounce);
}
};
Ball.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,2*Math.PI,false);
ctx.fillStyle = this.color;
ctx.fill();
};
var ctx, clock, ball
width = 300,
height = 150;
window.onload = function(){
ball = new Ball(20,150,30,4,0,"red");
var canvas = document.getElementById('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
clock = setInterval(main,33);
};
function main(){
ctx.clearRect(0,0,width,height);
ball.draw();
ball.move();
}
canvas{
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bouncy Balls</title>
<link rel="stylesheet" href="style.css">
<script src="ball.class.js"></script>
<script src="script.js"></script>
</head>
<body>
<div align="center">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
Upvotes: 2
Views: 137
Reputation: 866
I think your problem is that when your ball would bounce, it still gets accelerated downwards for the whole tick, and because of that it bounces up further than it should.
EDIT: Because of that, this only is a problem for the y-direction.
Upvotes: 1