首页 > 解决方案 > 改变移动方向时水平翻转图像

问题描述

我想让“ball.png”在移动过程中按 K_RIGHT 和 K_LEFT 时水平翻转。

我试图在 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)

标签: python-3.xpygame

解决方案


此代码未经测试,但它应该为您提供正确的逻辑。这也假设精灵的默认方向是左面的。

首先你需要知道他们面对的方向。你可以使用一个变量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))

推荐阅读