边界:
// 限定了探险者的运动边界,contain(explorer,state)
contain(explorer,{x:28,y:10,width:488,height:480});
function contain(sprite,container){
let collision = undefined;
// left
if(sprite.x < container.x){
sprite.x = container.x;
collision = "left";
}
// top
if(sprite.y < container.y){
sprite.y = container.y;
collision = "top";
}
// right
if(sprite.x + sprite.width > container.width){
sprite.x = container.width - sprite.width;
collision = "right";
}
// bottom
if(sprite.y + sprite.height > container.height){
sprite.y = container.height - sprite.height;
collision ="bottom";
}
return collision;
}
碰撞
hitTestRectangle(explorer,blob);//explorer,blob都是精灵
// 检测碰撞:先计算出explorer和blob的中心位置坐标,
// 再计算explorer和blob的中心距离(vx,vy),
// 再计算出explorer和blob的中心相加的距离(combinedHalfWidths,combinedHalfHeights),
// 通过判断vx的绝对值和combinedHalfWidths的大小,vy的绝对值和combinedHalfHeights的大小来判断是否发生碰撞
function hitTestRectangle(r1,r2){
let hit,combinedHalfWidths,combinedHalfHeights,vx,vy;
hit = false;
r1.centerX = r1.x + r1.width/2;
r1.centerY = r1.y + r1.height/2;
r2.centerX = r2.x + r2.width/2;
r2.centerY = r2.y + r2.height/2;
r1.halfWidth = r1.width/2;
r1.halfHeight = r1.height/2;
r2.halfWidth = r2.width/2;
r2.halfHeight = r2.height/2;
vx = r1.centerX - r2.centerX;
vy = r1.centerY - r2.centerY;
combinedHalfWidths = r1.halfWidth + r2.halfWidth;
combinedHalfHeights = r1.halfHeight + r2.halfHeight;
if(Math.abs(vx) < combinedHalfWidths && Math.abs(vy) < combinedHalfHeights){
hit = true;
}else{
hit = false;
}
return hit;
}
这两个可以作为函数封装好