【发布时间】:2018-04-17 10:48:41
【问题描述】:
我希望有一个 HTML5 画布,其中包含圆形元素和方形元素,它们在 cavnas 周围弹跳,但也相互弹跳和碰撞,希望在碰撞时旋转。
我找到的最接近的是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);
任何帮助将不胜感激。
【问题讨论】:
-
我认为这个问题太宽泛了。
-
您需要在当前圆圈 (i) 与所有其他圆圈(圆圈数组)之间添加一个循环比较,这样如果它们发生碰撞,它们就会在它们之间反弹。
标签: javascript html html5-canvas collision gravity