8.4.2.2_利用最小平移向量使两个物体粘在一起
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>利用最小平移向量使两个物体粘在一起</title>
<style>
body{
background: #fff;
}
#canvas{
background: #eee;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
</body>
<script>
var Sprite = function(name,painter,behaviors){
if(name !== undefined){ this.name = name; }
if(painter !== undefined){ this.painter = painter; }
this.top = 0;
this.left = 0;
this.width = 10;
this.height = 10;
this.velocityX = 0;
this.velocityY = 0;
this.visible = true;
this.animating = false;
this.behaviors = behaviors || [];
}
Sprite.prototype = {
paint:function(context){
if(this.painter !== undefined && this.visible){
this.painter.paint(this,context);
}
},
update:function(context,time){
for(var i=0;i<this.behaviors.length;i++){
this.behaviors[i].execute(this,context,time);
}
}
}
</script>
<script>
var ImagePainter = function (imageUrl){
var self = this;
this.image = new Image();
this.loaded = false;
this.image.src = imageUrl;
this.image.addEventListener('load',function(){
self.loaded = true;
},false);
}
ImagePainter.prototype ={
paint:function(sprite,context){
context.drawImage(this.image,sprite.left,sprite.top,sprite.width,sprite.height);
}
}
</script>
<script>
var Vector = function(x,y){
this.x = x;
this.y = y;
};
Vector.prototype = {
getMagnitude:function(){
return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2));
},
add:function(anotherVector){
var v = new Vector();
v.x = this.x + anotherVector.x;
v.y = this.y + anotherVector.y;
return v;
},
subtract:function(anotherVector){
var v = new Vector();
v.x = this.x - anotherVector.x;
v.y = this.y - anotherVector.y;
return v;
},
dotProduct:function(anotherVector){
return this.x *anotherVector.x+ this.y*anotherVector.y;
},
edge:function(anotherVector){
return this.subtract(anotherVector);
},
perpendicular:function(){
var v = new Vector();
v.x = this.y;
v.y = 0-this.x;
return v;
},
normalize:function(){
var v = new Vector(0,0);
var m = this.getMagnitude();
if(m!=0){
v.x = this.x/m;
v.y = this.y/m;
}
return v;
},
perpendicularNormal:function(){
var p = this.perpendicular();
return p.normalize();
}
}
</script>
<script>
var Projection = function(min,max){
this.min = min;
this.max = max;
};
Projection.prototype = {
overlaps:function(projection){
return this.max > projection.min && projection.max >this.min;
},
overlap : function(projection){
var minP = 10000;
if(this.max > projection.min && projection.max >this.min){
var pro1 = Math.abs(this.max - projection.min);
var pro2 = Math.abs(projection.max - this.min);
var pro3 = Math.abs(this.max - this.min );
var pro4 = Math.abs(projection.max - projection.min );
return Math.min(pro1,pro2,pro3,pro4);
}else{
return 0;
}