一切正常,但是我无法使程序打印(“完全向后”)和打印(“完全向右”)。我很确定我的值在if语句中是正确的。
我还有另一个程序,可以显示模拟摇杆的位置值和正确的值。我试图切换大于/小于大于的语句,但是什么也没做,我已经仔细检查了值。
joystick = pygame.joystick.Joystick(i)###########
joystick.init()
for i in range( 0, 2 ):
axis = joystick.get_axis( i )
#print('Axis {} value: {:>6.3f}'.format(i, axis))
axis0 = joystick.get_axis(0)
axis1 = joystick.get_axis(1)
#backward totally
if axis1 == 1.000:
print("backward totally")
#Nothing GOOD
if -.100 < axis0 < .100 and -.100 < axis1 < .100:
print('centered')
#forward totally GOOD
if axis1 == -1.000:
print('forward totally')
#left totally GOOD
if axis0 == -1.000 and -.599 < axis1 < 0.200:
print("left totally")
#right totallly
if axis0 == 1.000 and -.599 < axis1 < 0.200:
print('Right totally')
它不会给出错误,只是不打印任何内容,我也不知道为什么,我希望它可以完全正确打印或完全反向打印。
答案 0 :(得分:0)
我修改了代码中的条件语句,以添加“死区”和“边缘区”的概念。您可以将“死区”视为内半径,将在其中记录为“居中”的运动,而在较大外半径之外(即在边缘区域中)的运动是沿固定方向的运动。该代码可能是这样的:考虑到我的xbox 360控制器的布局,每个摇杆的复制肯定有改进的空间:
import pygame
pygame.init()
"""
Just a check to ensure a joystick is plugged in.
Only going to retrieve data for the 0th joystick anyways...
"""
num_joysticks = pygame.joystick.get_count()
if num_joysticks == 0:
raise ValueError("No joysticks attached!")
joystick = pygame.joystick.Joystick(0)
joystick.init()
#Just some info about the controller
j_id = joystick.get_id()
j_name = joystick.get_name()
num_axes = joystick.get_numaxes()
num_balls = joystick.get_numballs()
num_buttons = joystick.get_numbuttons()
num_hats = joystick.get_numhats()
print(j_id, j_name)
print(num_axes, num_balls, num_buttons, num_hats)
#Define the inner and outer radii that are considered 0 and 100% movement
dead_zone = 0.2#inner radius
edge_zone = 0.9#outer radius
while True:
for event in pygame.event.get():
pass
"""
Only have an xbox 360 controller to work with
There, axes 0 and 1 correspond the left stick x and y
And axes 3 and 4 correspond to the right stick x and y
Not sure what axes 2 and 5 are listed for...
For me, the ranges only go from [-1.0, 1.0), so 1.0 is not included for right and bottom.
"""
left_x = joystick.get_axis(0)
left_y = joystick.get_axis(1)
right_x = joystick.get_axis(3)
right_y = joystick.get_axis(4)
if (-dead_zone < left_x < dead_zone) and (-dead_zone < left_y < dead_zone):
print("Left stick centered")
elif left_x < -edge_zone:
print("Left stick is totally left")
elif left_x > edge_zone:
print("Left stick is totally right")
elif left_y < -edge_zone:
print("Left stick is totally up")
elif left_y > edge_zone:
print("Left stick is totally down")
else:
print("Left stick is somewhere")
if (-dead_zone < right_x < dead_zone) and (-dead_zone < right_y < dead_zone):
print("Right stick centered")
elif right_x < -edge_zone:
print("Right stick is totally left")
elif right_x > edge_zone:
print("Right stick is totally right")
elif right_y < -edge_zone:
print("Right stick is totally up")
elif right_y > edge_zone:
print("Right stick is totally down")
else:
print("Right stick is somewhere")