【问题标题】:How to move a box [ rectangle as square] up and down in pygame?如何在pygame中上下移动一个盒子[矩形为正方形]?
【发布时间】:2017-08-13 10:27:50
【问题描述】:

我正在尝试在pygame 中上下移动一个框。
我可以使用键 a 向左移动框,使用键 d 向右移动。
如何上下移动它?
我的代码:

import sys
import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    rect = pg.Rect(300, 220, 20, 20)
    velocity = (0, 0)
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:  #to move left
            rect.x -= 4
        if keys[pg.K_d]: #to move right
            rect.x += 4


        screen.fill((40, 40, 40))
        pg.draw.rect(screen, (150, 200, 20), rect)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    您可以使用与水平移动相同的逻辑,通过更改 y 坐标:

            y-4
             |
    x-4 <-- [_] --> x+4
             |
            y+4
    
    
    if keys[pg.K_w]: # to move up
        rect.y -= 4
    if keys[pg.K_s]: # to move down
        rect.y += 4
    

    【讨论】:

    • 我还有一个问题,如何设置界限?
    • @user8455923 你想在游戏屏幕上设置边界还是必须更小,比如盒子只能在特定单元格中移动?
    【解决方案2】:

    我认为按箭头键对移动框更有意义。

    (未完成的内部:循环)

    if event.type == pg.KEYDOWN:
        if event.key == pg.K_LEFT:
            rect.x -= 4
        if event.key == pg.K_RIGHT:
            rect.x += 4
        if event.key == pg.K_UP:
            rect.y -= 4
        if event.key == pg.K_DOWN:
            rect.y += 4
    

    【讨论】:

    • 我没有使用箭头键,因为它们不会让盒子连续移动。
    • 我们也可以使用if keys[pygame.K_UP]:等。
    猜你喜欢
    • 2023-01-10
    • 2021-02-06
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多