JS面向对象--打飞机实例解析(2)--敌方飞机的创建与移动

一.创建方法:
–构造函数定义敌方小飞机
(1)属性:
[1]图片节点
[2]图片
[3]x坐标
[4]y坐标
[5]速度
(2)行为:
[1]移动
[2]初始化 把图片节点添加到mainObj里
二.代码实现:
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 SmallPlaneProto(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();
		this.move=function(){
			this.imgNode.style.top=parseInt(this.imgNode.offsetTop)+this.speed+'px';

		}
	}

	function createSmallPlane(){
       var smallPlane=new SmallPlaneProto('../img/enemy1_fly_1.png',random(0,356),random(0,576),parseInt(random(1,5)))
       //下为将创建的实例化对象添加到数组smallPlaneArray中
       smallPlaneArray.push(smallPlane);
   }
//批量创建敌方小飞机
 setInterval(createSmallPlane,1000);

   //为实现敌方飞机的不同位置显示,即x,y坐标为随机值
  function random(min,max)
{
	return parseInt(Math.random()*(max-min)+min);
}
//函数实现每一台小飞机的移动
function smallPlaneMove(){
	for(i=0;i<smallPlaneArray.length;i++)
		{smallPlaneArray[i].move();
			//边界判断,即当小飞机离开background范围内时进行节点移除
			if(parseInt(smallPlaneArray[i].imgNode.offsetTop)>=600)
				{mainObj.removeChild(smallPlaneArray[i].imgNode);//移除子节点
					smallPlaneArray.splice(i,1);//数组中删除数组元素
				}
		}
}
//让实例中的move函数进行定时执行
setInterval(smallPlaneMove,50);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值