2017-06-19 101 views
1

我正在嘗試在連接了PS4控制器的屏幕上移動指定的球。我可以連接控制器,並在移動左側模擬杆時返回不同的值。我覺得屏幕只是需要更新?我很難搞清楚。Pygame遊戲杆控制 - 屏幕沒有更新?

下面是我有:

感謝

import pygame 

def main(): 

    pygame.init() 

    size = width, height = 800, 800 
    black = 0, 0, 0 
    speed = [5,5] 

    screen = pygame.display.set_mode(size) 
    ball = pygame.image.load("ball1.jpg") 
    ballrect = ball.get_rect() 

    pygame.joystick.init() 
    joysticks = [pygame.joystick.Joystick(x) for x in 
range(pygame.joystick.get_count())] 

    for joystick in joysticks: 
     joystick.init() 

    controller = joysticks[0] 

    while True: 

     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: sys.exit() 

     ballrect.move(speed) 
     if controller.get_axis(0) < -.5: 
      speed[0] = -speed[0] 

     if controller.get_axis(0) > .5: 
      speed[0] = speed[0] 

     if controller.get_axis(1) < -.5: 
      speed[1] = speed[1] 

     if controller.get_axis(1) > .5: 
      speed[1] = -speed[1] 

     screen.fill(black) 
     screen.blit(ball, ballrect) 
     pygame.display.flip() 

回答

0

Rect.move返回你必須分配給ballrect變量,例如一個新的矩形ballrect = ballrect.move(speed)。或者使用ballrect.move_ip(speed),它修改現有的矩形而不創建新的矩形。

控制器代碼似乎也被破壞了。試着這樣做:

# x and y axis positions of the stick (between -1.0 and 1.0). 
x_axis_pos = controller.get_axis(0) 
y_axis_pos = controller.get_axis(1) 
# Set the speed to a multiple of the axis positions. 
if x_axis_pos > .5 or x_axis_pos < -.5: 
    speed[0] = int(x_axis_pos * 5) 
else: 
    speed[0] = 0 
if y_axis_pos > .5 or y_axis_pos < -.5: 
    speed[1] = int(y_axis_pos * 5) 
else: 
    speed[1] = 0 
+0

我忘了提,你需要將速度設置爲0,如果值不是在'如果x_axis_pos> .5,或x_axis_pos <-0.5:'範圍。只需添加兩個'else'子句。 – skrx

+0

謝謝,這工作得很好!我很感激。 –