简体   繁体   中英

Using pygame Joystick in pyglet

I'm trying to write a simple game with pyglet but use pygame for gamepad input. The following code successfully prints axis values to the command line, but aside from importing pyglet, doesn't actually show a pyglet window:

import pygame
import math
import sys
import pyglet

pygame.init()
pygame.joystick.init()    
js = pygame.joystick.Joystick(0)
js.init()

while True:
    pygame.event.get()
    jx = js.get_axis(0)    
    print('axis 0: ' + str(jx))

I'm not sure what role pygame.event.get() plays, but without it, the returned axis value is always just zero.

So now when I try to use the Joystick in my pyglet events, I always just get zero as the value (even if I hold the stick in position and move the window around to trigger draw events):

import pygame
import math
import sys
import pyglet

pygame.init()
pygame.joystick.init()    
js = pygame.joystick.Joystick(0)
js.init()

window = pyglet.window.Window()

@window.event
def on_draw():
    jx = js.get_axis(0)    
    print('axis 0: ' + str(jx))
    window.clear()

pyglet.app.run()

If I toss a pygame.event.get() into on_draw(), I get a blank white window which I can't drag with no console output (until I hit esc, closing the window and exiting, at which point several axis values get printed, all zero). Is event.get() stuck blocked?

So despite what is suggested at https://groups.google.com/forum/?fromgroups=#!msg/psychopy-users/GWNE4RvGbRE/TNRKM1L2PBwJ , using pygame Joystick seems to involve more than just importing it and initializing.

Perhaps if I use pygame's event handling it would work, but that might have its own problems when drawing with pyglet from a pygame even handler.

好吧,我将通过使用Pyglet 1.21alpha(包括操纵杆支持)来回避此问题。

I think your problem was that you didn't put it in a while loop. That way it doesn't just print once, so for example your function (which I haven't tested) but should work, looks something like this.

def on_draw():
 while True:
  jx = js.get_axis(0)
  print('axis 0: '+ str(jx))
  window.clear()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM