gpt4 book ai didi

javascript - 自己的物理引擎 : Bouncing doesn't stop

转载 作者:行者123 更新时间:2023-11-28 00:58:49 28 4
gpt4 key购买 nike

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

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>

最佳答案

我认为你的问题是,当你的球弹跳时,它仍然会在整个滴答声中向下加速,因此它弹跳得比它应该的更远。

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

关于javascript - 自己的物理引擎 : Bouncing doesn't stop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206393/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com