1.创建原理部分:
–构造函数定义玩家飞机
(1)属性:
[1]图片节点
[2]图片
[3]x坐标
[4]y坐标
[5]速度
(2)行为:
[1]移动–>上下左右
[2]发射子弹
[3]初始化 把图片节点添加到mainObj里
2.代码实现部分:
html+css
<!--下为css部分,主要是背景图的设置-->
*{margin:0;padding:0;}
#main{width:400px;
height:600px;
background:url("../img/background_1.png");
margin:30px auto;
position:relative;
overflow:hidden;}
<!--下为div主要是背景图设置-->
<div id="main"></div>
JS部分:
//下为创建玩家飞机实例
function PlayerPlaneProto(imgSrc,x,y,speed){
this.imgNode=document.createElement('img');
this.imgSrc=imgSrc;
this.x=x;
this.y=y;
this.speed=speed;
//初始化方法
this.init=function(){
this.imgNode.src=this.imgSrc;
this.imgNode.style.position='absolute';
this.imgNode.style.left=this.x+'px';
this.imgNode.style.top=this.y+'px';
mainObj.appendChild(this.imgNode);
}
//页面加载完成后直接调用
this.init();
//在实例化对象PlayPlaneProto中根据按键添加移动的值
//到时候根据判断玩家按键来执行的相应的事件
//左
this.moveLeft=function(){
this.imgNode.style.left=parseInt(this.imgNode.offsetLeft)-this.speed+'px';
}
//右
this.moveRight=function(){
this.imgNode.style.left=parseInt(this.imgNode.offsetLeft)+this.speed+'px';
}
//上
this.moveTop=function(){
this.imgNode.style.top=parseInt(this.imgNode.offsetTop)-this.speed+'px';
}
//下
this.moveBottom=function(){
this.imgNode.style.top=parseInt(this.imgNode.offsetTop)+this.speed+'px';
}
//玩家飞机发射子弹事件
this.shoot=function(){
}
}
var player=new PlayerPlaneProto('../img/myplane.gif',50,500,10);
// ------------------------------------------------------------------
//玩家飞机的移动
//在body按下键盘的时候 移动玩家飞机
document.onkeydown=function(e){
var ev=e||window.event;
if(ev.keyCode==37)//左
// {player.moveLeft();//由系统执行,显得移动比较卡顿
{leftBtn=true;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==38)//上
// {player.moveTop();//由系统执行,显得移动比较卡顿
{topBtn=true;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==39)//右
// player.moveRight();//由系统执行,显得移动比较卡顿
{rightBtn=true;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==40)//下
// player.moveBottom();//由系统执行,显得移动比较卡顿
{bottomBtn=true;}//加入控制变量,用函数加快按键执行,此处选择这个方法
}
//当抬起时关闭控制按键让控制函数停止执行
document.onkeyup=function(e){
var ev=e||window.event;
if(ev.keyCode==37)//左
// {player.moveLeft();//由系统执行,显得移动比较卡顿
{leftBtn=false;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==38)//上
// {player.moveTop();//由系统执行,显得移动比较卡顿
{topBtn=false;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==39)//右
// player.moveRight();//由系统执行,显得移动比较卡顿
{rightBtn=false;}//加入控制变量,用函数加快按键执行,此处选择这个方法
else if(ev.keyCode==40)//下
// player.moveBottom();//由系统执行,显得移动比较卡顿
{bottomBtn=false;}//加入控制变量,用函数加快按键执行,此处选择这个方法
}
//控制函数控制上下左右键
function ctrlPlay()
{
if(leftBtn==true)
{player.moveLeft();}
if(rightBtn==true)
{player.moveRight();}
if(topBtn==true)
{player.moveTop();}
if(bottomBtn==true)
{player.moveBottom();}
}
//控制函数执行时间,由定时器执行函数监听
setInterval(ctrlPlay,50);