停止在重力作用下弹跳球消失

时间:2016-03-23 03:37:59

标签: javascript processing p5.js

我想模拟一个球弹跳,并在未来创造更多并让他们反弹。这是我的代码(使用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属性,显然不会滚动,但在弹跳停止后停止移动)

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

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

如果您想要恢复原状,请在每次碰撞后将其应用于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;
        }
    }
};

答案 1 :(得分:0)

我可以通过两次调整来更接近地模拟一个弹跳球:

  1. 如果球碰到地板,请不要施加重力。
  2. 每次反弹时
  3. 衰减减少速度
  4. 一旦幅度足够小,将速度设置为0
  5. 更新退回:

    // Attenuate velocity by making the magnitude of this value < 1
    var bounce = -0.9;
    
    // Give initial vy
    var vy = 0.1;
    

    并且确保我们只在球是空气时才增加重力&#34; (阻止我们的球离开地面#34;):

    function draw() {
        background(0);
    
        ellipse(xpos, ypos, diameter, diameter);
    
        var floor = windowHeight - diameter/2;
        var inAir = ypos <= floor;
        var moving = Math.abs(vy) > 0.01;
    
        if (inAir && moving) {
            vy += gravity;
        }
    
        ypos += vy;
    
        if(!inAir && vy > 0) {
            vy *= bounce;
    
            if (!moving) {
                vy = 0;
            }
        }
    }
    
相关问题