pygame 如何用摇杆让精灵上下移动

how to make sprite move upwards and downwards with joystick in pygame

我正在尝试创建一个我以前做过的项目,但除此之外,我将使用学校免费提供的一个遥控器。当我向上和向下移动操纵杆时,它显示相同坐标的问题。(如果你不明白我的意思,请看下图)。然后我也不确定我需要在 if 语句中放入什么,以便它检查操纵杆是向上还是向下。我也无法思考如何检查操纵杆是否没有朝任何方向移动。

我已经尝试使用 if 语句,其中如果操纵杆大于一个数字且小于另一个数字(第一个数字在操纵杆的上半部分,另一个数字意味着它在底部)摇杆的一半它会向下移动。当前的 if 语句没有给出任何错误但不起作用。我已经尝试过 if 语句来检查它是否在中间但我不太确定。

    joystick_count = pygame.joystick.get_count()
if joystick_count == 0:
    # No joysticks!
    print("Error, I didn't find any joysticks.")
else:
    # Use joystick #0 and initialize it
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

if pygame.joystick.Joystick(0).get_axis(0) >= -0.0 and pygame.joystick.Joystick(0).get_axis(0) <= 0.0:
      player_one.speed_y = 5

elif pygame.joystick.Joystick(0).get_axis(0) > -0.1 and pygame.joystick.Joystick(0).get_axis(0) < -0.9:
    player_one.speed_y = -5

elif pygame.joystick(0).get_axis(0) == 0.0:
    player_one.speed_y = -5



#The first if statement checks if the joystick is up and the second one
#checks if the joystick is downwards
# the middle one checks if the if statement is in the middle (not too sure)
#player one and two speed is what gets added on each time

实际结果是摇杆向下移动时精灵不移动

Joystick axis

首先确保你有一个操纵杆,通过pygame.joystick.get_count(). Initialize the joystick by pygame.joystick.Joystick.init获取操纵杆的数量:

joystick = None
if pygame.joystick.get_count() > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

操纵杆初始化后,可以通过pygame.joystick.Joystick.get_axis获取ist轴值。此函数返回的值在 [-1, 1] 范围内。 -1 表示最大负倾斜,+1 表示最大正倾斜。
请注意,游戏手柄或操纵杆的每个模拟摇杆都有 2 个轴,一个用于水平方向,1 个用于垂直方向。由于 get_axis() 返回的值的数量取决于模拟摇杆的倾斜度,因此您应该将速度乘以该值。
此外,由于硬件的不准确性,您应该忽略死点接近 0 的值。这可以通过使用内置函数 abs(x) 的简单检查来完成,例如abs(axisval) > 0.1:

if joystick:
    axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
    if abs(axis_x) > 0.1:
        player_one.speed_x = 5 * axis_x
    if abs(axis_y) > 0.1:
        player_one.speed_y = 5 * axis_y

请参阅以下简单的演示应用程序:

import pygame
pygame.init()

size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
pos = [size[0]/2, size[1]/2]
speed = 5
joystick = None

done = False
while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key==pygame.K_RETURN:
                done = True

    if joystick:
        axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
        if abs(axis_x) > 0.1:
            pos[0] += speed * axis_x
        if abs(axis_y) > 0.1:
            pos[1] += speed * axis_y
    else:
        if pygame.joystick.get_count() > 0:
            joystick = pygame.joystick.Joystick(0)
            joystick.init()
            print("joystick initialized")

    screen.fill((0, 0, 255))
    pygame.draw.rect(screen, (255,255,255), (*pos, 10, 10))
    pygame.display.flip()