实现效果:
canvas实现矩形碰撞
有关于【孤寒者】:
作者介绍:【孤寒者】—全栈领域优质创作者、HDZ核心组成员、华为云享专家Python全栈领域博主、原力计划作者 |
- 本文已收录于Python全栈系列专栏:《前端系列教程》
- 热门专栏推荐:《Django框架从入门到实战》、《爬虫从入门到精通系列教程》、《爬虫高级》、《前端系列教程》、《tornado一条龙+一个完整版项目》。
- 本专栏面向广大程序猿,为的是大家都做到Python从入门到精通,同时穿插有很多很多习题,巩固学习。
- 加入我一起学习进步,一个人可以走的很快,一群人才能走的更远!
源码:
<!DOCTYPE html>
<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.w = randomNum(10,100);
// 矩形高
this.h = randomNum(10,60);
// 矩形左上x
this.x = randomNum(0,c.width - this.w);
// 矩形左上y
this.y = randomNum(0,c.height - this.h);
// 矩形的颜色
this.color = randomColor();
// 矩形的速度
this.speedX = randomNum(-5,5);
this.speedY = randomNum(-5,5);
// 绘制自身
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
ctx.fill();
};
// 移动
this.move = function(){
if(this.x <= 0 || this.x + this.speedX + this.w > c.width){
this.speedX *= -1;
};
if(this.y <= 0 || this.y + this.speedY + this.h > 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;
}
}
}
};
};
// 产生一个范围Wie[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){
if(ball1.x > ball2.x+ball2.w || ball1.y > ball2.y + ball2.h || ball1.x + ball1.w < ball2.x || ball1.y < ball2.y){
return false;
}else{
return true;
}
}</script>
</html>