快速编程JS初级教程3-2 循环地图

效果:


技术要点:

左右两段相同的地图背景,共1000px。游戏画布宽500px。

初始化,地图左上角坐标(0,0),让地图向左移动,当横坐标变为-500,再设置为0,这就实现了循环移动。

代码:

<script>
// http://www.w3school.com.cn
var o = document.body; 
var gframe;//游戏画布div
var role2;//地图div
var mapx=0;//地图横坐标

function init()
{
	gframe = document.createElement("div"); 
	gframe.style = 'background-color:#ff0000;width:500px; height : 400px;position:relative;overflow:hidden'; 
	gframe.id="game1";
	o.appendChild(gframe);	
	
	role2= document.createElement("div"); 
	role2.style = 'width:1000px; height : 400px;position : absolute;top :100px;left: 0px'; 
	role2.id="divmap";
	gframe.appendChild(role2);
	
	initmap();
}
function initmap()
{
	  var strcontext="";
	  strcontext+='<img src="img/back1.png" ></img>';
	   strcontext+='<img src="img/back1.png" ></img>';
	for(var i=0;i<20;i++)
	{
		
		strcontext+='<img src="img/role2.png" style="width:50px; height : 50px; "></img>';
	}
	role2.innerHTML=strcontext;
 }

function gameupdate()
{
	mapx-=10;
	if(mapx<-500)
		mapx=0;
	
	var divmap=document.getElementById("divmap");
	divmap.style.left=mapx;
}

init();
var int=self.setInterval("gameupdate()",200);

</script>

游戏场景,一般用循环地图在背景素材,整个关卡的地图,仍然是单张地图,最后留一个boss. 

休闲游戏中,重复的部分就用这个循环的技术来做,同时,随机产生一些游戏元素,例如金币、道具等。

猜你喜欢

转载自blog.csdn.net/weixin_42644456/article/details/81059375