<!DOCTYPE html>
<html lang=
"en"
>
<head>
<meta charset=
"UTF-8"
>
<title>Title</title>
<style>
html
{
background-color: deepskyblue;
}
div
{
width: 32px;
height: 32px;
background-image: url(
"img/Actor01-Braver03.png"
);
position: absolute;
}
</style>
</head>
<body>
<div></div>
<script>
var
key=0;
var
bool=
false
;
var
speed=2;
var
actor;
const HEIGHT=33;
const WIDTH=32;
var
arr=[1,3,2,0];
var
num=0;
var
jumpBool=
false
;
var
actorSkinSpeed=8;
var
jumpSpeed=-15;
init();
function
init() {
window.addEventListener(
"keydown"
,keyHandler);
window.addEventListener(
"keyup"
,keyHandler);
actor=document.querySelector(
"div"
);
setInterval(animation,16);
}
function
keyHandler(e) {
bool=e.type===
"keydown"
;
key=e.keyCode;
if
(!bool){
num=0;
actor.style.backgroundPositionX=-num*WIDTH+
"px"
;
}
if
(key===32 && !jumpBool){
jumpBool=
true
;
}
}
function
animation() {
jump();
if
(!bool)
return
;
walk();
changeDirection();
}
function
jump() {
if
(!jumpBool)
return
;
jumpSpeed+=1;
if
(jumpSpeed===15){
jumpBool=
false
;
jumpSpeed=-15;
return
;
}
actor.style.top=actor.offsetTop+jumpSpeed+
"px"
;
}
function
changeDirection() {
actorSkinSpeed--;
if
(actorSkinSpeed>0)
return
;
actorSkinSpeed=8;
num++;
if
(num>3) num=0;
actor.style.backgroundPositionX=-num*WIDTH+
"px"
;
}
function
walk() {
switch
(key){
case
37:
actor.style.left=actor.offsetLeft-speed+
"px"
;
actor.style.backgroundPositionY=-arr[0]*HEIGHT+
"px"
;
break
;
case
38:
actor.style.top=actor.offsetTop-speed+
"px"
;
actor.style.backgroundPositionY=-arr[1]*HEIGHT+
"px"
;
break
;
case
39:
actor.style.left=actor.offsetLeft+speed+
"px"
;
actor.style.backgroundPositionY=-arr[2]*HEIGHT+
"px"
;
break
;
case
40:
actor.style.top=actor.offsetTop+speed+
"px"
;
actor.style.backgroundPositionY=-arr[3]*HEIGHT+
"px"
;
break
;
}
}
</script>
</body>
</html>