gpt4 book ai didi

javascript - 阻止重力作用下的弹跳球消失

转载 作者:行者123 更新时间:2023-12-02 14:51:16 26 4
gpt4 key购买 nike

我想模拟一个球的弹跳,并在将来创建更多球并使它们反弹。这是我的代码(使用 p5.js,一个 JavaScript 处理库)

var xpos = 200;
var ypos = 450;
var vy = 0;
var gravity = 0.6;
var bounce = -1.00;
var diameter = 30;

function setup() {
var myCanvas = createCanvas(windowWidth, windowHeight);

stroke(255);
noFill();
}

function draw() {
background(0);

ellipse(xpos, ypos, diameter, diameter);

vy += gravity;
ypos += vy;

if(ypos > (windowHeight - diameter/2)) {
vy *= bounce;
}

}

看起来好像工作正常,但是当弹跳非常小时,它开始出现故障并消失,here's a codepen 。我不知道如何让它停止并滚动或其他什么(如果没有 x 属性,显然不会滚动,但只是在弹跳停止后停止移动)

感谢任何帮助,谢谢。

最佳答案

您想要首先应用加速度,然后进行碰撞测试,然后调整碰撞位置。

如果您想要恢复原状,请在每次碰撞后将其应用于 vy,例如

编辑:还使用检查来查看对象是否应该“休息”有帮助

var xpos = 200;
var ypos = 0;
var vy = 0;
var gravity = 10;
var bounce = 0.9; // typically represented as a positive normalized value
var diameter = 30;
var sleepTolerance = gravity; // this will provide a solid result

// KA variables
var windowHeight = height;
var windowWidth = width;

frameRate(30);
var draw = function() {
background(0);

ellipse(xpos, ypos, diameter, diameter);

var asleep = false;

if(!asleep){
vy += gravity;
ypos += vy;
}

var heightAboveGround = ypos - (windowHeight - diameter/2);
if(heightAboveGround > 0) { // remember y is inverted
// position adjusted for reflection after collision
// including restitution (resulting from the bounce)
ypos -= bounce * heightAboveGround;

// apply restitution to subsequent velocity
vy *= -bounce;

if (heightAboveGround <= sleepTolerance && abs(vy) <= sleepTolerance){
asleep = true;
ypos = windowHeight - diameter/2;
}
}
};

关于javascript - 阻止重力作用下的弹跳球消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36169379/

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