37-陨石对象原型
8.14 陨石对象原型
为了节省篇幅,没有为游戏中不同的显示对象都创建独立的对象原型。不过,例8-12给出了陨石的原型对象Rock。该原型可被用于其他类似Geo Blaster Basic的游戏中。
例8-12 Rock.js的原型
//*** 陨石对象原型
function Rock(scale, type){
//大小
//1=大型
//2=中型
//3=小型
//这些值将作为除数,用于计算计算新的大小
//50/1=50
//50/2=25
//50/3=16
this.scale=scale;
if (this.scale <1 || this.scale >3){
this.scale=1;
}
this.type = type;
this.dx=0;
this.dy=0;
this.x=0;
this.y=0;
this.rotation=0;
this.rotationInc=0;
this.scoreValue=0;
//ConsoleLog.log("create rock. Scale=" + this.scale);
switch(this.scale){
case 1:
this.width=50;
this.height=50;
break;
case 2:
this.width=25;
this.height=25;
break;
case 3:
this.width=16;
this.height=16;
break;
}
}
Rock.prototype.update=function(xmin,xmax,ymin,ymax){
this.x+=this.dx;
this.y+=this.dy;
this.rotation+=this.rotationInc;
if (this.x > xmax){
this.x=xmin-this.width;
}else if (this.x<xmin-this.width){
this.x=xmax;
}
if (this.y > ymax){
this.y=ymin-this.width;
}else if (this.y<ymin-this.width){
this.y=ymax;
}
}
Rock.prototype.draw=function(context){
var angleInRadians = this.rotation * Math.PI / 180;
var halfWidth=Math.floor(this.width*.5); //用于计算对象的中心
var halfHeight=Math.floor(this.height*.5)// 用于计算对象的中心
context.save(); //在栈中保存当前状态
context.setTransform(1,0,0,1,0,0); // 重置变换矩阵
//将画布从原点平移到陨石的中心
context.translate(this.x+halfWidth,this.y+halfHeight);
context.rotate(angleInRadians);
context.strokeStyle = '#ffffff';
context.beginPath();
//绘制每个物体时偏移1/2. 零相对于1/2是 .5*width -1. 计算高度时相同
context.moveTo(-(halfWidth-1),-(halfHeight-1));
context.lineTo((halfWidth-1),-(halfHeight-1));
context.lineTo((halfWidth-1),(halfHeight-1));
context.lineTo(-(halfWidth-1),(halfHeight-1));
context.lineTo(-(halfWidth-1),-(halfHeight-1));
context.stroke();
context.closePath();
context.restore(); //恢复原有状态到屏幕
}
//*** Rock类结束