1024programmer Java Example of using keyboard to control character movement implemented in JavaScript_javascript skills

Example of using keyboard to control character movement implemented in JavaScript_javascript skills

In fact, this example uses two core times of js, the keyboard event onkeydown and the periodic execution event setInterval.

Achieve results

When a certain key on the keyboard is pressed, the characters on the web page will perform corresponding actions, achieving the effect of using the keyboard to control movement

Implementation steps

1. Function of reservation key:

w: up
s: downward
a: to the left
d: Right
Space: Stop

2. After booking the key value, it is necessary to capture the key event and determine which key the user pressed?

To capture keyboard events you can use onkeydown
To obtain the key-value code, you can use event.keyCode

3. Use setInterval periodic execution event to replace the picture

Replacing pictures is to achieve the task walking effect
But be careful to use clearInterval to clear the cycle execution, otherwise it will go faster and faster

Sample code:


 	
 		
 		
 	
 	
 
  • w: up
  • s: down
  • a: left
  • d: right
  • Space: Stop
  • Script Home

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/629654

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索