0

我一直在尝试使用诸如pynput等库中的一些“密钥释放”函数,但我遇到了一个问题,如果我尝试将它们与一个名为pyglet的库一起使用,它是一个基于窗口的应用程序的库,它不会让我和程序会崩溃。

我想知道是否有任何方法可以检测没有库的关键版本。

PS:我尝试过使用on_key_releasepyglet 中的函数,但它对我来说是错误的,即使我在密钥释放时为它写了一些东西,它通常也不会这样做。我已经检查了我的代码一千次,这对我来说不是问题。

Pressing = False # var to indicate when the user is doing a long press and when he is not
@window.event
def on_key_release(symbol, modifiers):
    global Pressing
    if((symbol == key.A) | (symbol == key.S) | (symbol == key.W) | (symbol == key.D)):
        Pressing = False
    pass

并且该代码导致我的播放器在我开始移动他后冻结,即使我什么都不做并且只是将整个 on_key_release 函数过滤为空,它也会这样做。真的很奇怪。

4

1 回答 1

0

Pressing = False因此,如果释放任何密钥,您的问题很可能是您正在做的。一旦你释放任何键,就会强制你的播放器对象冻结PressingFalse

要解决这个问题,您应该将键的状态存储在一个变量中(我称之为self.keys),并且在渲染内容之前,更新/检查键并相应地更新您的播放器对象。

这是一个在玩家对象(本例中为红色方块)上移动的工作示例:

from pyglet import *
from pyglet.gl import *

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)
        self.x, self.y = 0, 0

        self.keys = {}

        self.mouse_x = 0
        self.mouse_y = 0

        square = pyglet.image.SolidColorImagePattern((255, 0, 0, 255)).create_image(40, 40)
        self.player_object = pyglet.sprite.Sprite(square, x=self.width/2, y=self.height/2)

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse_x = x

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        ## Movement logic,
        #  check if key.W is in self.keys (updated via key_press and key_release)
        if key.W in self.keys:
            self.player_object.y += 1
        if key.S in self.keys:
            self.player_object.y -= 1
        if key.A in self.keys:
            self.player_object.x -= 1
        if key.D in self.keys:
            self.player_object.x += 1

        self.player_object.draw()

        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

if __name__ == '__main__':
    x = main()
    x.run()

我已经离开了,@window.event因为我更容易复制粘贴这个类/继承示例,因为我已经放置了它。但是你可以以任何你想要的方式应用这个逻辑。只需确保您没有定义按下或不按下的固态,在渲染之前检查各个键并进行相应更新。

于 2019-10-23T13:50:37.893 回答