我有一块画布,球/硬币掉在其中,然后从地板,侧壁和彼此反弹。没有实施天花板。这一切都很好,直到引入了太多的球为止。
发生这种情况时,球开始相互融合,甚至不时突破边界。我相信这与增加球的重力有关,但是如果我知道,那我就不会在这里:D任何帮助都将受到赞赏!
https://codepen.io/cb2003/pen/joQaWZ
在第21 && 23行中,您可以设置要丢弃的硬币数量。
21| const coin_1 = 50;
23| const coin_2 = 50;
// Objects
function Ball(x, y, dy, dx, radius, color) {
this.x = x
this.y = y
// this.dy = dy;
// this.dx = dx;
this.velocity = {
x:dx,
y:dy
}
this.radius = radius
this.color = color
this.mass = 1;
this.collision = ()=> {
for (var index = 0; index < objects.length; index++) {
var coin = objects[index];
if (this === coin) {
continue;
}
if (getDistance(this.x, this.y, coin.x, coin.y) - (this.radius + coin.radius) < 0) {
// alert('hi');
console.log("collision:");
resolveCollision(this, coin)
}
}
}
}
Ball.prototype.update = function() {
if (this.y + this.radius + this.velocity.y > canvas.height) {
this.velocity.y = (-this.velocity.y * parseFloat(0.85));
}else {
this.velocity.y += gravity;
}
this.y += this.velocity.y;
this.x += this.velocity.x;
if (this.x + this.radius + this.velocity.x > canvas.width) {
this.velocity.x = -this.velocity.x;
}
if (Math.sign(this.velocity.x) === 1) {
this.velocity.x -= 0.01;
} else if (Math.sign(this.velocity.x) === -1) {
this.velocity.x += 0.01;
}
if (this.x - this.radius - this.velocity.x < 0) {
this.velocity.x = Math.abs(this.velocity.x);
}
this.draw()
}
如何使这些元素堆叠在另一个之上?我能想到的唯一方法是,递归检查每个球是否正在接触地板,或者另一个球是否正在接触地板,或者另一个球,等等:D尽管更喜欢