2017-04-04 48 views
2

我创建了一个简单的Ball原型,其中包括draw()move()函数。球应该在地板,墙壁和天花板上弹跳。然而,出于某种原因,尽管速度(vy)得到的值不断下降,但它并不会停止弹跳......你知道我做错了什么吗?自己的物理引擎:弹跳不停止

function Ball(radius,x,y,vx,vy,color){ 
 
\t this.radius = radius; 
 
\t this.x = x; 
 
\t this.y = y; 
 
\t this.vx = vx; 
 
\t this.vy = vy; 
 
\t this.color = color; 
 
\t this.gravity = 0.6; 
 
\t this.friction = { 
 
\t \t air: 0.005, 
 
\t \t bounce: 0.3 
 
\t }; 
 
} 
 

 
Ball.prototype.move = function(){ 
 
\t this.x += this.vx; 
 
\t this.y += this.vy; 
 
\t //Gravity 
 
\t this.vy += this.gravity; 
 
\t //Air Friction 
 
\t this.vx /= 1+this.friction.air; 
 
\t this.vy /= 1+this.friction.air; 
 
\t //Bounce Border 
 
\t if(this.x<this.radius){//Left 
 
\t \t this.x = this.radius+((this.radius-this.x)/(1+this.friction.bounce)); 
 
\t \t this.vx /= -(1+this.friction.bounce); 
 
\t } 
 
\t if(this.x>width-this.radius){//Right 
 
\t \t this.x = (width-this.radius)-((this.x-(width-this.radius))/(1+this.friction.bounce)); 
 
\t \t this.vx /= -(1+this.friction.bounce); 
 
\t } 
 
\t if(this.y<this.radius){//Top 
 
\t \t this.y = this.radius+((this.radius-this.y)/(1+this.friction.bounce)); 
 
\t \t this.vy /= -(1+this.friction.bounce); 
 
\t } 
 
\t if(this.y>height-this.radius){//Bottom 
 
\t \t this.y = (height-this.radius)-((this.y-(height-this.radius))/(1+this.friction.bounce)); 
 
\t \t this.vy /= -(1+this.friction.bounce); 
 
\t } 
 
}; 
 

 
Ball.prototype.draw = function(){ 
 
\t ctx.beginPath(); 
 
\t ctx.arc(this.x,this.y,this.radius,0,2*Math.PI,false); 
 
\t ctx.fillStyle = this.color; 
 
\t ctx.fill(); 
 
}; 
 

 
var ctx, clock, ball 
 
\t width = 300, 
 
\t height = 150; 
 

 
window.onload = function(){ 
 
\t ball = new Ball(20,150,30,4,0,"red"); 
 
\t var canvas = document.getElementById('canvas'); 
 
    canvas.width = width; 
 
    canvas.height = height; 
 
\t ctx = canvas.getContext('2d'); 
 
\t clock = setInterval(main,33); 
 
}; 
 

 
function main(){ 
 
\t ctx.clearRect(0,0,width,height); 
 
\t ball.draw(); 
 
\t ball.move(); 
 
}
canvas{ 
 
\t background-color: black; 
 
}
<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <meta charset="utf-8"> 
 
\t \t <title>Bouncy Balls</title> 
 
\t \t <link rel="stylesheet" href="style.css"> 
 
\t \t <script src="ball.class.js"></script> 
 
\t \t <script src="script.js"></script> 
 
\t </head> 
 
\t <body> 
 
\t \t <div align="center"> 
 
\t \t \t <canvas id="canvas"></canvas> 
 
\t \t </div> 
 
\t </body> 
 
</html>

回答

1

我觉得你的问题是,当你的球会反弹,但仍然被向下为全剔加快,因为它比它应该进一步反弹向上。

编辑: 因此,这只是y方向的问题。

+1

听起来似乎是合理的...那么你会如何做到这一点? –