Home >Web Front-end >JS Tutorial >How to use keyboard events to realize character walking in js
Pictures used:
Rendering pictures:
( Recommended tutorial: javascript tutorial)
Example code:
<!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;//人物div const HEIGHT=33;//人物的高 const WIDTH=32;//人物的宽 var arr=[1,3,2,0];//4排图像 代表 下 左 右 上 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://左 ×1 第二排 actor.style.left=actor.offsetLeft-speed+"px"; actor.style.backgroundPositionY=-arr[0]*HEIGHT+"px"; break; case 38://上 ×3 第四排 actor.style.top=actor.offsetTop-speed+"px"; actor.style.backgroundPositionY=-arr[1]*HEIGHT+"px"; break; case 39://右 ×2 第三排 actor.style.left=actor.offsetLeft+speed+"px"; actor.style.backgroundPositionY=-arr[2]*HEIGHT+"px"; break; case 40://下 ×0 第一排 actor.style.top=actor.offsetTop+speed+"px"; actor.style.backgroundPositionY=-arr[3]*HEIGHT+"px"; break; } } </script> </body> </html>
Recommended related video tutorial:javascript video tutorial
The above is the detailed content of How to use keyboard events to realize character walking in js. For more information, please follow other related articles on the PHP Chinese website!