0
点赞
收藏
分享

微信扫一扫

canvas实现动态小球碰撞

实现效果:


canvas实现动态小球碰撞

源码:


<html>
<head>
<meta charset="UTF-8">
<title>小球碰撞title>
<style type="text/css">
#c{
border: 1px solid red;
}
style>
head>
<body>

<canvas id="c" width="1400" height="700">canvas>

body>
<script type="text/javascript">
var c = document.getElementById("c");
var ctx = c.getContext("2d");

// 定义一个数组,用于存放小球。
var ballArr = []

for(var i = 0;i < 10; i++){
// 创建小球
var b = new Ball();
// 把小球放入数组
ballArr.push(b); // 把小球放到数组的末尾。
}

// 递归+requestAnimationFrame()方法实现小球运动
function startGame(){
// 清空画布
ctx.clearRect(0,0,c.width,c.height);
// 把数组中的小球画出来
for(var i = 0; i < ballArr.length; i++){
// 绘制小球
ballArr[i].draw();
// 小球移动
ballArr[i].move();
}
requestAnimationFrame(startGame); // requestAnimationFrame的作用就是重绘
};

// 开始
startGame()

function Ball(){
// 半径
this.r = randomNum(10,50);
// 圆心坐标
this.x = randomNum(this.r,c.width-this.r);
this.y = randomNum(this.r,c.height-this.r);
// 圆的颜色
this.color = randomColor();
// 球的速度
this.speedX = randomNum(-10,10);
this.speedY = randomNum(-10,10);
// 绘制自身
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.fill();
};
// 移动
this.move = function(){
// 定义左右边界
if(this.x + this.r + this.speedX > c.width || this.x - this.r < 0){
this.speedX *= -1;
};
// 定义上下边界
if(this.y - this.r < 0 ||this.y + this.r > c.height){
this.speedY *= -1;
};
// 移动
this.x += this.speedX;
this.y += this.speedY;

// 判断当前的小球和其他小球有没有相交
// 需要逐个判断:
for(var i = 0; i < ballArr.length; i++){
// 如果数组中的球不是我自身(当前球)
if(this != ballArr[i]){
if(interect(this,ballArr[i])==true){
// 交换颜色
var tempColor = this.color;
this.color = ballArr[i].color;
ballArr[i].color = tempColor;


// 交换x方向速度
var tempSpeedX = this.speedX;
this.speedX = ballArr[i].speedX;
ballArr[i].speedX = tempSpeedX;
// 交换y方向速度
var tempSpeedY = this.speedY;
this.speedY = ballArr[i].speedY;
ballArr[i].speedY = tempSpeedY;

}
}
}
};
};


// 产生一个范围[min,max]的随机数
function randomNum(min,max){
// 思路:[20,80]---->[0,60] + 20 Math.floor()向下取整。
var num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
};


// 产生一个随机颜色
function randomColor(){
var r = randomNum(0,255);
var g = randomNum(0,255);
var b = randomNum(0,255);

var c = "rgb("+r+","+g+","+b+")";
return c;
};


// 判断两个圆是否相交
function interect(ball1,ball2){
var dx = ball1.x - ball2.x;
var dy = ball1.y - ball2.y;
var distance = Math.sqrt(dx*dx+dy*dy);
if(ball1.r + ball2.r >= distance){
// 半径之和大于等于圆心距离,说明相交了
return true;
}else{
return false;
}
}


script>
html>


举报

相关推荐

0 条评论