<style>
#actor{
width: 32px;
height: 33px;
position: absolute;
background-image: url(./img/Actor01-Braver03.png);
left: 0;
top: 0;
}
</style>
<body>
<div id="#actor"></div>
<script>
const STEP=15;
var actor;
var x=0,y=0,speedX=0.3,speedY=0.3,n=0,keyList=[40,37,39,38],key=-1,time=STEP;
init();
function init(){
actor=document.querySelector("#actor");
document.addEventListener("keydown",keyHandler);
document.addEventListener("keyup",keyHandler);
setInterval(animation,16);
}
function keyHandler(e){
key=keyList.indexOf(e.keyCode);
if(!~key) return;
if(e.type==="keydown"){
actor.style.backgroundPositionY=key*-33+"px";
}else if(e.type==="keyup"){
key=-1;
time=STEP;
n=0;
actor.style.backgroundPositionX="0px";
}
}
function animation(){
if(!~key) return;
actorMove();
changeAction();
}
function changeAction(){
time--;
if(time>0)return;
n=(++n)%4;
time=STEP;
actor.style.backgroundPositionX=n*-32+"px";
}
function actorMove(){
key===0 ? y+=speedY : key===1 ? x-=speedX : key===2 ? x+=speedX : y-=speedY;
actor.style.left=x+"px";
actor.style.top=y+"px";
}
</script>
</body>