js实现游戏⼈物⾏⾛及障碍物事件⼈物⾏⾛事件实现
话不多说 直接上代码
var hero;
const DOWN=Symbol(),
LEFT=Symbol(),
RIGHT=Symbol(),
UP=Symbol(),
TIME_STEP=9;
var n=0,bool=false,x=32,y=32,state=0,speed=1,time=TIME_STEP;
init();
function init() {
createMap();
createHero();
document.addEventListener("keydown",keyHandler);
document.addEventListener("keyup",keyHandler);
setInterval(animation,16);
}
function createMap() {
js 二维数组var table = ateElement("table");
Object.assign(table.style, {
position: "relative",
borderCollapse: "collapse",
top: 0,
left: 0,
});
for (var i = 0; i < map.length; i++) {
var tr = ateElement("tr");
for (var j = 0; j < map[i].length; j++) {
var td = ateElement("td");
Object.assign(td.style, {
width: "32px",
height: "32px",
backgroundImage:
"url(./img/item_" +
(map[i][j] === 3 ? 12 : map[i][j]) +
".png)",
backgroundSize: "100% 100%",
});
if (map[i][j] === 3) {
var img = new Image();
img.src = "./img/item_3.png";
td.appendChild(img);
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
function createHero(){
ateElement("div");
Object.assign(hero.style,{
width:"32px",
height:"33px",
position:"absolute",
left:"32px",
top:"32px",
top:"32px",
backgroundImage:"url(./img/Actor01-Braver03.png)",
backgroundPositionX:"0px",
backgroundPositionY:"0px"
});
document.body.appendChild(hero);
}
function keyHandler(e){
if(e.keyCode<37 || e.keyCode>40) return;
var s= e.keyCode ===37 ? LEFT : e.keyCode===38 ? UP : e.keyCode===39 ? RIGHT : DOWN;
if(s!==state){
state=s;
hero.style.backgroundPositionY=-33*(state===DOWN ? 0 : state===LEFT ? 1 : state===RIGHT ? 2 : 3)+"px"; }
pe==="keydown";
pe==="keyup")hero.style.backgroundPositionX="0px";
}
function animation(){
if(!bool) return;
heroStateChange();
heroMove();
}
function heroStateChange(){
time--;
if(time>0)return;
time=TIME_STEP;
n++;
if(n>3)n=0;
hero.style.backgroundPositionX=-n*32+"px";
}
function heroMove(){
var x1=x,y1=y;
switch(state){
case UP:
y1-=speed;
break;
case DOWN:
y1+=speed;
break;
case LEFT:
x1-=speed;
break;
case RIGHT:
x1+=speed;
break;
}
var row=Math.floor(y1/32);
var col=Math.floor(x1/32);
if(map[row][col]!==12) return;
x=x1;
y=y1;
hero.style.left=x+"px"
p=y+"px"
}
document.addEventListener("click",clickhandlers);
function clickhandlers(){
state=DOWN;//执⾏
// state=Symbol();
// state=Symbol();
bool=true;
}
事件关键代码就是这些,具体地图如何⽤⼆维数组创建等可以私信我要源码
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论