jQuery change image src attribute

2019-07-21 06:05发布

Right now I'm trying make some browser based game. But I have little questions. Please open below code and inspect it.

http://jsfiddle.net/thisizmonster/YVz6L/4/

  1. Is there any better solutions handle keyboard inputs?
  2. While moving, i'm changing image with Running soldier. But as you can see my soldier not running, but after stopped press key, it will start run. Why its happening?

1条回答
不美不萌又怎样
2楼-- · 2019-07-21 06:34

1) I wonder whether it would be better to only move your character on keydown and stop him on keyup. You'd have to be careful though, as not all elements support the method. I've seen examples before where a form element is placed offscreen (e.g. position:absolute; left:-999px;), and given focus as the page loads. The form field then accepts keypresses and the key handlers are assigned to it.

2) Is because you're constantly resetting the image src to the run image, which means it keeps going to the first frame. You could get round this by incrementing a counter while the key is down, and only changing the image when the counter == 1. You'd also need to detect the release of the key, so you can change the image back and reset the counter to 0.

查看更多
登录 后发表回答