我正在为我的程序制作游戏,当我按左键或右键时,我正试图水平翻转图像。我发现了函数
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
答案 0 :(得分:2)
当玩家实例化时,我会做图像处理的东西:
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))
这是我对所有动画游戏对象采用的方法。