我想在移动过程中同时按下K_RIGHT和K_LEFT来使“ ball.png”水平翻转。
我试图在Ball类中插入pygame.transform.flip(self.image,True,False),但是随后我在定义移动键时设法将所有内容都拧紧了。
您能建议我最简单,最简单的方法吗? :)我正在尝试学习,因此每一个解释都将非常有用。
这是我正在运行atm的代码。
import pygame
import os
size = width, height = 750, 422
screen = pygame.display.set_mode(size)
img_path = os.path.join(os.getcwd())
background_image = pygame.image.load('background.jpg').convert()
pygame.display.set_caption("BallGame")
class Ball(object):
def __init__(self):
self.image = pygame.image.load("ball.png")
self.image_rect = self.image.get_rect()
self.image_rect.x
self.image_rect.y
def handle_keys(self):
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN] and self.image_rect.y < 321:
self.image_rect.y += dist
elif key[pygame.K_UP] and self.image_rect.y > 0:
self.image_rect.y -= dist
if key[pygame.K_RIGHT] and self.image_rect.x < 649:
self.image_rect.x += dist
elif key[pygame.K_LEFT] and self.image_rect.x > 0:
self.image_rect.x -= dist
def draw(self, surface):
surface.blit(self.image,(self.image_rect.x,self.image_rect.y))
pygame.init()
screen = pygame.display.set_mode((750, 422))
ball = Ball()
clock = pygame.time.Clock()
running = True
while running:
esc_key = pygame.key.get_pressed()
for event in pygame.event.get():
if esc_key[pygame.K_ESCAPE]:
pygame.display.quit()
pygame.quit()
running = False
ball.handle_keys()
screen.blit(background_image, [0, 0])
ball.draw(screen)
pygame.display.update()
clock.tick(40)
答案 0 :(得分:0)
此代码未经测试,但应为您提供正确的逻辑。同样,这假定子画面的默认方向是朝左的。
首先,您需要知道他们面对的方向。您可以使用变量facing
def __init__(self):
self.image = pygame.image.load("ball.png")
self.image_rect = self.image.get_rect()
self.image_rect.x
self.image_rect.y
self.facing = "LEFT"
当您按向右或向左时,您需要改变面容:
def handle_keys(self):
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN] and self.image_rect.y < 321:
self.image_rect.y += dist
elif key[pygame.K_UP] and self.image_rect.y > 0:
self.image_rect.y -= dist
if key[pygame.K_RIGHT] and self.image_rect.x < 649:
self.facing = "RIGHT"
self.image_rect.x += dist
elif key[pygame.K_LEFT] and self.image_rect.x > 0:
self.facing = "LEFT"
self.image_rect.x -= dist
最后,您需要根据脸部正确显示图像:
def draw(self, surface):
if self.facing == "RIGHT":
surface.blit(pygame.transform.flip(self.image, True, False),(self.image_rect.x,self.image_rect.y))
else:
surface.blit(self.image,(self.image_rect.x,self.image_rect.y))