HTML5弹跳元素

时间:2018-04-17 10:48:42

标签: javascript html5 html5-canvas collision gravity

我希望有一个带有圆形元素和方形元素的HTML5画布在空腔周围弹跳,但也会相互弹跳并相互碰撞,希望在碰撞时旋转。

我发现最接近的是https://codepen.io/gichmbugua/pen/LpZWgo

var canvas = document.getElementById("my_canvas");
var c = canvas.getContext("2d");

//create te container that will hold the boincing balls.
var container = {
    x: 0,
    y: 0,
    width: 600,
    height: 300
};
//create the array of circles that will be animated
var circles = [{
    x: 50,
    y: 100,
    r: 10,
    vx: 10,
    vy: 9,
    color: 125
}, {
    x: 150,
    y: 80,
    r: 20,
    vx: 15,
    vy: 8,
    color: 205
}, {
    x: 90,
    y: 150,
    r: 5,
    vx: 5,
    vy: 15,
    color: 25
}, {
    x: 100,
    y: 50,
    r: 15,
    vx: 8,
    vy: 10,
    color: 100
}];

function animate() {
    //draw the container
    c.fillStyle = "#000000";
    c.fillRect(container.x, container.y, container.width, container.height);

    //loop throughj the circles array
    for (var i = 0; i < circles.length; i++) {
        //draw the circles
        c.fillStyle = 'hsl(' + circles[i].color++ + ', 100%, 50%)';
        c.beginPath();
        c.arc(circles[i].x, circles[i].y, circles[i].r, 0, Math.PI * 2, true);
        c.fill()

        //time to animate our circles ladies and gentlemen.
        if (circles[i].x - circles[i].r + circles[i].vx < container.x || circles[i].x + circles[i].r + circles[i].vx > container.x + container.width) {
            circles[i].vx = -circles[i].vx;
        }

        if (circles[i].y + circles[i].r + circles[i].vy > container.y + container.height || circles[i].y - circles[i].r + circles[i].vy < container.y) {
            circles[i].vy = -circles[i].vy;
        }

        circles[i].x += circles[i].vx
        circles[i].y += circles[i].vy
    }

    requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

对于其他正方形或每个圆圈与其他圆圈的每个正方形,您可以使用a basic collision detection

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}

var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected!
}

然后改变速度和方向的归属方式。

对于方形和圆形之间的碰撞检测,您可以检查this question

小心比较同一步骤的位置,以避免将更新后的值与旧值进行比较。例如,您可以使用圆圈副本。

prevCircles = JSON.parse(JSON.stringify(circles));