繁体   English   中英

如何在JavaScript中模拟弹跳?

[英]How can I simulate a bounce in JavaScript?

我试图使矩形因重力而下落,当矩形碰到画布底部时会反弹,并在几次反弹后停止。

在下面的代码中,我的矩形在碰到画布底部后将以额外的力量启动。 将加速度设置为零后,我确定方程的速度部分有问题。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// System settings
var restitution = -0.7;
var a = -32/Math.pow(1000,2); // acceleration

var myRectangle = {};

var draw = {
    rectangle: function (x, y, width, height) {
        context.beginPath();
        context.rect(x, y, height, width);
        context.fillStyle = '#8ED6FF';
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = 'black';
        context.stroke();
    }
};

function init() {
    myRectangle = {
        width   : 100,
        height  : 100,
        p_0     : {x:canvas.width/2, y:canvas.height/2},
        p       : {x:canvas.width/2, y:canvas.height/2},
        v_0     : {x:0, y:0},
        v       : {x:0, y:0},
        t_0     : (new Date()).getTime(),
        t       : 0
    };
    animate();
}

function animate() {

    // Bounce on the bottom
    if (    (myRectangle.p.y <= myRectangle.height)
        &&  (myRectangle.v.y < 0)){

        // Create new initial conditions on bounce
        myRectangle.p.y = myRectangle.height;
        myRectangle.p_0 = myRectangle.p;
        myRectangle.v_0.y = restitution * myRectangle.v.y;
        myRectangle.t_0 = (new Date()).getTime();
    }

    // Update rectangle time and position
    myRectangle.t = ((new Date()).getTime() - myRectangle.t_0);
    myRectangle.v.y = a*myRectangle.t + myRectangle.v_0.y;
    myRectangle.p.y = a*Math.pow(myRectangle.t,2)/2 + myRectangle.v_0.y * myRectangle.t + myRectangle.p_0.y;

    context.clearRect(0, 0, canvas.width, canvas.height);
    draw.rectangle(myRectangle.p.x, canvas.height-myRectangle.p.y, myRectangle.width, myRectangle.height);

    window.requestAnimationFrame(animate);
}

事实证明,方程式的初始位置部分实际上是一个错误。 我不能简单地将一个对象设置为与另一个对象相等,而是必须分别复制其属性。 解决方案如下:

// Bounce on the bottom
    if (    (myRectangle.p.y <= myRectangle.height)
        &&  (myRectangle.v.y < 0)){
        // Create new initial conditions on bounce
        myRectangle.p.y = myRectangle.height;

        // THIS LINE WAS INCORRECT
        myRectangle.p_0.y = myRectangle.p.y;

        myRectangle.v_0.y = restitution * myRectangle.v.y;
        myRectangle.t_0 = (new Date()).getTime();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM