[英]Pygame: Flipping horizontally
I'm making a game for my program and I'm trying to flip the image horizontally when I press the left key or right key. 我正在为我的程序制作游戏,并且在我按向左键或向右键时试图水平翻转图像。 I found out about the function
我发现了有关功能
pygame.transform.flip
however I am unsure as to where to insert it in my code. 但是我不确定在代码中插入的位置。 It would be appreciated if someone could help me.
如果有人可以帮助我,将不胜感激。 Here is my code.
这是我的代码。 Also could somebody also tell me how I could prevent the image from moving out of the screen?
还可以有人告诉我如何防止图像移出屏幕吗?
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
I would do the image processing stuff when Player is instantiated like so: 实例化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
Handle keys would changed the state of self.flipped. 手柄键会改变self.flipped的状态。
if key[pygame.K_RIGHT]:
self.x += dist
self.flipped = False
elif key[pygame.K_LEFT]:
self.x -= dist
self.flipped = True
Then self.draw decides which image to display. 然后self.draw决定要显示的图像。
def draw(self, surface):
if self.flipped:
image = self.image2
else:
image = self.image
surface.blit(image, (self.x, self.y))
This is the approach I take with all animated game objects. 这是我对所有动画游戏对象所采取的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.