<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="cont" width="500" height="500" style="border: 50px ridge blueviolet;"></canvas>
</body>
<script type="text/javascript">
var cont = document.getElementById("cont");
var z = cont.getContext("2d");
var ch = cont.height,cw = cont.width;
//创建一个矩形的类
function REC (x,y,w,h,color,speedx,speedy) {
this.color = color;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speedx = speedx;
this.speedy = speedy;
//画矩形
this.draw = function () {
z.fillStyle = this.color;
z.fillRect(this.x,this.y,this.w,this.h);
z.fill();
}
//增加一个运动的方法
this.move = function () {
this.x += this.speedx;
this.y += this.speedy ;
//判断触边
if (this.x<=0||this.x>=cw-this.w) {
this.speedx*=-1;
};
if (this.y<=0||this.y>=ch-this.h) {
this.speedy*=-1;
}
}
}
var rec2 = new REC(80,0,100,100,"red",1,1);
var rec1 = new REC(400,300,80,80,"green",1,1);
var direction = [];//定义存方向的数组
//碰撞检测
function peng (rec1,rec2) {
var x1=rec1.x,//1
y1=rec1.y,
w1=rec1.w,
h1=rec1.h,
x1y = rec1.speedy,
x1x = rec1.speedx;
var x2=rec2.x,//2
y2=rec2.y,
w2=rec2.w,
h2=rec2.h,
x2y = rec2.speedy,
x2x = rec2.speedx;
//上下碰
// if (y1+h1>=y2 && y2+h2>=y1&& x1+w1==x2&&x2+w2==x1) {
// x1x *=-1,x2x*=-1;
// console.log(x1x)
// return direction[0] = x1x,direction[1] = x2x;
//
// }
//左右碰
if (x1+w1>=x2 && y1+h1>=y2 &&x2+w2>=x1 && y2+h2>=y1) {
if(x1+w1==x2 || x2+w2==x1){
//左右碰
return 1
}
if(y1+h1==y2||y2+h2==y1){
//上下碰
return 2
}
}
return false;
}
console.log(peng (rec1,rec2))
function anmiate () {
//清除画布
z.clearRect(0,0,500,500);
if(peng(rec1,rec2)==1){
rec1.speedx*=-1;
// rec1.speedy*=-1;
rec2.speedx*=-1;
// rec2.speedy*=-1;
}
if(peng(rec1,rec2)==2){
// rec1.speedx*=-1;
rec1.speedy*=-1;
// rec2.speedx*=-1;
rec2.speedy*=-1;
}
rec1.draw(),rec1.move();
rec2.draw(),rec2.move();
window.requestAnimationFrame(anmiate);
}
anmiate();
</script>
</html>
以上,不过关于碰撞后的逻辑没改,但是个人觉得这个地方是有问题的,得看lz自己设计了。
如果按照现有逻辑,改变移动速度之后会导致一定诡异情况发生,比如同方向追及之后同时反向,以及某些情况下鬼畜效果。