首页 > 代码库 > canvas检测边界和弹动的实例
canvas检测边界和弹动的实例
如图所示的效果,小球相互碰撞会相互弹开,这时要干的事就只有两件事了,一:用二次循环遍历小球是否互相碰撞,二:碰撞之后会弹向什么地方和弹出多少距离,第一件事我想学过二维数组循环的都没问题,第二件事也只是用上期次弹动讲到的三角函数来判断角度,因为是力是相互的,所以反弹的一方应该是负值,而且因为撞击力会抵消,所以应该在乘以系数之后再乘以0.5这样就是相互弹撞,为了让效果明显,可以让反弹系数变成0.5,这样在弹在墙上就会变缓慢,效果就会变得更好
讲了这么多还是老规矩,代码贴上
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var Cleft = Ctop = 0;
var Cright = canvas.width;
var Cbottom = canvas.height;
var balles = [];
var spring = 0.03;
var bounce = -0.8;
var friction = 1;
function Ball(x, y, radius, vx, vy, color) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = radius;
this.color = color;
}
var ballA = new Ball(canvas.width / 2, canvas.height / 2, 40)
function animation() {
cxt.clearRect(0, 0, canvas.width, canvas.height);
cxt.beginPath();
cxt.fillStyle = "#fff";
balles.forEach(function(ball, i) {
ball.x += ball.vx;
ball.y += ball.vy;
if(ball.x + ball.radius > Cright || ball.x - ball.radius < Cleft) {
if(ball.x + ball.radius > Cright)
ball.x = Cright - ball.radius;
else
ball.x = Cleft + ball.radius;
ball.vx *= bounce;
}
if(ball.y + ball.radius > Cbottom || ball.y - ball.radius < Ctop) {
if(ball.y + ball.radius > Cbottom)
ball.y = Cbottom - ball.radius;
else
ball.y = Ctop + ball.radius;
ball.vy *= bounce;
}
for(var j=0;j<balles.length;j++){
checkCollision(ball,balles[j]);
}
cxt.beginPath();
cxt.fillStyle = ball.color;
cxt.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, true);
cxt.fill();
cxt.closePath();
})
requestAnimationFrame(animation);
}
function checkCollision(ballA,ballB){
var dx = ballA.x - ballB.x;
var dy = ballA.y - ballB.y;
var dist = Math.sqrt(dx * dx + dy * dy);
var mindist = ballB.radius + ballA.radius;
if(dist < mindist) {
var angle = Math.atan2(dy, dx);
var targetX = ballB.x + Math.cos(angle)*mindist;
var targetY = ballB.y + Math.sin(angle)*mindist;
var vx= (targetX - ballA.x) * spring*0.5;
var vy= (targetY - ballA.y) * spring*0.5;
ballA.vx += vx;
ballA.vy += vy;
ballB.vx += -(vx);
ballB.vy += -(vy);
}
ballA.vx *= friction;
ballA.vy *= friction;
}
window.onload = function() {
for(var i = 0; i < 20; i++) {
var x = tool.random(30, canvas.width - 30);
var y = tool.random(30, canvas.height - 30);
var vx = tool.random(3, 6);
var vy = tool.random(3, 5);
var radius = tool.random(10, 20);
var color = "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16)
balles.push(new Ball(x, y, radius, vx, vy, color));
}
animation();
}
canvas检测边界和弹动的实例