python-3.x - 改变移动方向时水平翻转图像
问题描述
我想让“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)
解决方案
此代码未经测试,但它应该为您提供正确的逻辑。这也假设精灵的默认方向是左面的。
首先你需要知道他们面对的方向。你可以使用一个变量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))
推荐阅读
- java - MediaPlayer 流服务中的 ProtocolException (MediaHTTPConnection: readAt 20709376 / 32768 => java.net.ProtocolException)
- android - 使用 setOnClickListener Kotlin 在 android 中执行应用程序时出错
- c# - C#比较两个强类型列表
- python - 如何使嵌套列表表现得像 numpy 数组?
- python - Python电报机器人 - AttributeError:'sqlite3.Cursor'对象没有属性'data_filter'
- java - Java NIO解码过程中如何去掉不正确的符号?
- android - Nativescript Angular-“typeof View”类型上不存在属性“SYSTEM_UI_FLAG_IMMERSIVE_STICKY”
- sockets - 具有相同本地地址的套接字能否同时处于两种状态“LISTEN”和“ESTABLISHED”
- c# - 使用 C# 访问 JSON 正文
- sql - Oracle SQL - 插入到选择语句中 - 错误