如何在 Pygame 中移动一个对象?

3

我一直试图使用用户输入只移动一个方块,但是当我尝试时,两个方块会同时移动而不是一个,这与我的目标不符。如何只移动一个方块(使用用户输入)而不是同时移动两个方块?谢谢:^)

import pygame
pygame.init()

pygame.display.set_caption('Crash!')
win = pygame.display.set_mode((800, 600))

x = 150
y = 300
width = 100
height = 60
scHeight = 600
scWidth = 800
vel = 0.5

running = True

while running:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP] and y > vel:
        y -= vel
    if keys[pygame.K_DOWN] and y < scHeight - height - vel:
        y += vel
    win.fill((0, 0, 0))
    plane = pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
    meteor = pygame.draw.rect(win, (255, 255, 0), (700, y, width, height))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
2个回答

0

PyGame只是在你告诉它的坐标处绘制你想要绘制的形状。
因此,如果我们看一下两个pygame.draw.rect()调用,我们可以看到两者都有y,所以当你在用户输入时更新y值时,你会“移动”两个矩形。


0

为方块使用单独的位置:

x1, y1 = 150, 300
x2, y2 = 700, 300

因此,每个立方体的位置都可以单独更改。例如,一个立方体可以通过箭头键移动,而另一个可以通过ws移动

keys = pygame.key.get_pressed()

if keys[pygame.K_UP] and y2 > vel:
    y2 -= vel
if keys[pygame.K_DOWN] and y2 < scHeight - height - vel:
    y2 += vel
if keys[pygame.K_w] and y1 > vel:
    y1 -= vel
if keys[pygame.K_s] and y1 < scHeight - height - vel:
    y1 += vel

每个对象都在自己的位置上绘制id。
plane = pygame.draw.rect(win, (255, 0, 0), (x1, y1, width, height))
meteor = pygame.draw.rect(win, (255, 255, 0), (x2, y2, width, height))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接