我正试图在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()
答案 0 :(得分: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
答案 1 :(得分:-1)
我认为按下方向键会更有意义移动方框。
(内部未完成:循环)
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