I'm trying to move a sprite while a key is pressed. I can do it with on_key_press() and on_key_release(), but with these I run into problems with moving right while holding left and vice versa. I'd like to use key polling and found this from the pyglet documentation.
from pyglet.window import key
window = pyglet.window.Window()
keys = key.KeyStateHandler()
window.push_handlers(keys)
# Check if the spacebar is currently pressed:
if keys[key.SPACE]:
pass
I don't seem to be able to implement this in cocos2d. A simple example is below. It prints 'Key Press!' just fine, but if I could get it to print 'Space!' repeatedly when the space key is pressed it would solve my problem.
from cocos.director import director
from cocos.layer import *
from cocos.scene import Scene
from pyglet.window import key
from pyglet.window.key import KeyStateHandler
class MyLayer(Layer):
is_event_handler = True
def __init__(self):
super(MyLayer, self).__init__()
self.keys = KeyStateHandler()
director.window.push_handlers(self.keys)
def on_key_press(self, symbol, modifiers):
print('Key press!')
if self.keys[key.SPACE]:
print('Space!')
def main():
director.init(resizable=False, width=1024, height=786)
title_scene = Scene(MyLayer())
director.run(title_scene)
if __name__ == '__main__':
main()
For completeness here is my on_key_press(), on_key_release() code. The problem is that if I press Right, press Left, release Left my Sprite will be stopped since the on_key_release() sets the x velocity to zero. But, I'm still pressing Right so I want to continue moving that directions after pressing and releasing Left.
def on_key_press(self, symbol, modifiers):
if symbol == key.LEFT:
self.player1.velocity = (-self.player1.speed, self.player1.velocity[1])
if symbol == key.RIGHT:
self.player1.velocity = (self.player1.speed, self.player1.velocity[1])
def on_key_release(self, symbol, modifiers):
if symbol == key.LEFT:
self.player1.velocity = (0, self.player1.velocity[1])
if symbol == key.RIGHT:
self.player1.velocity = (0, self.player1.velocity[1])