python - 试图让我的播放器transform.flip python

标签 python python-3.x pygame transform flip

我在 pygame 上苦苦挣扎。我希望当我分别按下右键或左键时,我的玩家移动并面向右或左。相反,它只是翻转。我不知道如何让它指向左边,或者右边,然后走路。

run = True

while run:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_RIGHT:
                swordsman = pg.transform.flip(swordsman, True, False)
                x += speed

            if event.key == pg.K_LEFT:
                swordsman = pg.transform.flip(swordsman, True, False)
                x -= speed

最佳答案

您可以使用 pg.key.get_pressed() 检查按键的状态查看是否按下了 (如下例所示),或者将 speed 变量更改为事件循环中的另一个值然后在 while 循环中而不是在事件循环中更改每帧的 x 位置 (x += speed)(释放按键时将速度重置为 0)。

关于图像翻转,保留对原始图像的引用并将其分配给swordsman变量。当玩家想要向另一个方向移动时,翻转原始图像并分配它(如果他们向原始方向移动,则分配原始图像)。

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# This is the original swordsman image/surface (just a
# rectangular surface with a dark topleft corner).
SWORDSMAN_ORIGINAL = pg.Surface((30, 50))
SWORDSMAN_ORIGINAL.fill((50, 140, 200))
pg.draw.rect(SWORDSMAN_ORIGINAL, (10, 50, 90), (0, 0, 13, 13))
# Assign the current swordsman surface to another variable.
swordsman = SWORDSMAN_ORIGINAL
x, y = 300, 200
speed = 4

run = True
while run:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_RIGHT:
                # When the player presses right, flip the original
                # and assign it to the current swordsman variable.
                swordsman = pg.transform.flip(SWORDSMAN_ORIGINAL, True, False)
            elif event.key == pg.K_LEFT:
                # Here you can just assign the original.
                swordsman = SWORDSMAN_ORIGINAL

    # Check the state of the keys each frame.
    keys = pg.key.get_pressed()
    # Move if the left or right keys are held.
    if keys[pg.K_LEFT]:
        x -= speed
    elif keys[pg.K_RIGHT]:
        x += speed

    screen.fill(BG_COLOR)
    screen.blit(swordsman, (x, y))
    pg.display.flip()
    clock.tick(60)

pg.quit()

关于python - 试图让我的播放器transform.flip python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064358/

相关文章:

python - %load_ext rpy2.ipython 错误

python - 使用 Flask-SQLAlchemy 批量插入

python - 字典的嵌套合并

python - 类型错误 : to_excel() got multiple values for argument 'sheet_name'

python - 乘客数量。错误 : list indices must be integers or slices, 未列出

python - 导入错误 : No module named serial

python - 尝试在 pygame 中播放动画会导致错误

python - pygame 一次一个级别的组织和运行函数

python - Pandas 系列箱线图未正确显示

python - 如何显示在类中创建的矩形?