且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在pygame中水平翻转图像?

更新时间:2023-11-09 13:05:46

添加猪的方向变量.将其设置为按下键,请勿将其更改为重新按下键.使运动依赖于moving_direction变量,显示的sprite依赖于direction变量.

Add a pig orientation variable. Set it on key down, don't change it back on key up. Have movement rely on the moving_direction variable and the sprite displayed rely on the orientation variable.

像这样更改blitme:

Change blitme like so:

def blitme(self):
    if self.orientation == "Right":
        self.screen.blit(self.image, self.rect)
    elif self.orientation == "Left":
        self.screen.blit(pygame.transform.flip(self.image, False, True), self.rect)

然后,您可以像这样设置按键逻辑:

Then you can have your key press logic like so:

elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                pig.moving_right = True
                pig.orientation = "Right"
            elif event.key == pygame.K_LEFT:
                pig.moving_left = True
                pig.orientation = "Left"
            elif event.key == pygame.K_UP:
                pig.moving_up = True
            elif event.key == pygame.K_DOWN:
                pig.moving_down = True

通过这种方式,您可以将显示和移动逻辑分开.

In this way you can separate display and movement logic.