1. 程式人生 > >二十八、JS飛機大戰demo

二十八、JS飛機大戰demo

var shouter;function Shouter(){this.width=10;this.height=20;this.shouterf=null;this.position="absolute";this.src="./image/15.png";this.x;this.y;//構造建立子彈的方法this.creatShouter=function(User){if(this.shouterf==null){this.shouterf=document.createElement("img");this.shouterf.style.width=this.width+"px";this.shouterf

.style.height=this.height+"px";this.shouterf.style.position=this.position;this.shouterf.style.zIndex=1;this.shouterf.src=this.src;map.appendChild(this.shouterf);//子彈座標 x=飛機left+飛機自身的一半-子彈自身一半            //y=飛機top-飛機自身的一半this.x=parseInt(user.userf.style.left)+user.width/2-this.width/2;this.y=parseInt(user.
userf.style.top)-user.height/2;        }this.shouterf.style.left=this.x+"px";this.shouterf.style.top=this.y+"px";    };//構造子彈移動的方法this.ShouterMove=function(index,array){this.y-=2; //子彈的top值if(this.y<=0){//當子彈飛出螢幕 移除建立的子彈及其例項化物件this.shouterf.remove();            array.splice(index,1);//移除例項化陣列中的子彈 利用陣列擷取的方法
}this.creatShouter();//改變top後繼續建立子彈形成連續發射效果};

}

由於子彈是動態變化時建立的,所以使用定時器呼叫子彈類

//例項化子彈 呼叫建立方法time_creatShouter=setInterval(function(){shouter=new Shouter();shouter.creatShouter(user);shout.push(shouter);},200);

由於是改變每顆子彈自身的top值,所以呼叫子彈移動方法時需遍歷子彈陣列,注意先得判斷是否有子彈生成

//呼叫子彈移動方法time_ShouterMove=setInterval(function(){if(shout.length>0){for(var i=0;i<shout.length;i++){shout[i].ShouterMove(i,shout);          }},5);

四、敵機的建立及移動

分析:1.敵機也是一組屬性類似的資料,故定義陣列來儲存;

2.同樣需要建立敵機類,敵機用圖片表示,這裡建立2種敵機,大敵機和小敵機;

注意:將小敵機的屬性設定為預設值,大敵機屬性傳引數設定;

3.構造敵機的下落方法與子彈原理一致,即改變每個敵機的top屬性值;

注意:當敵機飛出地圖,需移除建立建立方法的敵機還有其例項化物件,同樣用例項化儲存敵機的陣列擷取的方法實現;

/*建立敵機 封裝敵機類*/var enemy;function Enemy(width,height,blood,score,s){//敵機分為2種this.width=width||40;this.height=height||30;this.blood=blood||3;this.score=score||100;this.enemyf=null;this.src=s||"./image/17.png";this.speed=2;this.position="absolute";this.x;//x軸 leftthis.y;//y軸 top    //構造建立敵機的方法this.createEnemy=function(){if(this.enemyf==null){this.enemyf=document.createElement("img");this.enemyf.style.width=this.width+"px";this.enemyf.style.height=this.height+"px";this.enemyf.style.position=this.position;this.enemyf.style.zIndex=2;this.enemyf.src=this.src;map.appendChild(this.enemyf);//隨機產生起始線不同位置的敵機this.x=Math.random()*(400-this.width);this.y=-this.height;        }this.enemyf.style.left=this.x+"px";this.enemyf.style.top=this.y+"px";    }//構造敵機下落的方法this.EnemyMove=function(index,array){//改變敵機的top值 賦回去this.y+=this.speed;if(this.y>630){//敵機飛出介面 移除建立的敵機