簡體   English   中英

Pygame:水平翻轉

[英]Pygame: Flipping horizontally

我正在為我的程序制作游戲,並且在我按向左鍵或向右鍵時試圖水平翻轉圖像。 我發現了有關功能

pygame.transform.flip

但是我不確定在代碼中插入的位置。 如果有人可以幫助我,將不勝感激。 這是我的代碼。 還可以有人告訴我如何防止圖像移出屏幕嗎?

import pygame
import os

img_path = os.path.join('C:\Python27', 'player.png')

class Player(object):  
    def __init__(self):
        self.image = pygame.image.load("player1.png")

        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 5
        if key[pygame.K_DOWN]: 
            self.y += dist 
        elif key[pygame.K_UP]: 
            self.y -= dist 
        if key[pygame.K_RIGHT]: 
            self.x += dist 
        elif key[pygame.K_LEFT]:
            self.x -= dist
)

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))


pygame.init()
screen = pygame.display.set_mode((640, 400))

player = Player() 
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()      # quit the screen
            running = False

    player.handle_keys()       # movement keys

    screen.fill((255,255,255)) # fill the screen with white
    player.draw(screen)        # draw the player to the screen
    pygame.display.update()    # update the screen

    clock.tick(60)             # Limits Frames Per Second to 60 or less

實例化Player時,我將進行圖像處理:

class Player(object):  
    def __init__(self):
        self.image = pygame.image.load("player1.png")
        self.image2 = pygame.transform.flip(self.image, True, False)
        self.flipped = False
        self.x = 0
        self.y = 0

手柄鍵會改變self.flipped的狀態。

    if key[pygame.K_RIGHT]: 
        self.x += dist
        self.flipped = False
    elif key[pygame.K_LEFT]:
        self.x -= dist
        self.flipped = True

然后self.draw決定要顯示的圖像。

def draw(self, surface):
    if self.flipped:
        image = self.image2
    else:
        image = self.image
    surface.blit(image, (self.x, self.y))

這是我對所有動畫游戲對象所采取的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM