The major issue in your code is, that when you press and LEFT, then press and hold RIGHT and finally release LEFT, the resulting states of accel_x
and accel_y
are both 0, because the last event that happend was pygame.KEYUP
.
我建议评估以下状态pygame.key.get_pressed()而不是使用关键事件:
- If UP is pressed and DOWN is not pressed, the increment
y_change
up to its maximum (y_change = max(y_change-0.2, -max_speed)
).
- If UP is not pressed and DOWN is pressed, the decrement
y_change
down to its minimum (y_change = min(y_change+0.2, max_speed)
).
- 如果同时按下两个键或没有按下任何一个键,则降低速度(
y_change *= 0.98
).
Apply the same principle to x_change
, when the keys LEFT and/or RIGHT are pressed:
![](https://i.stack.imgur.com/XNhzy.gif)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
keys = pygame.key.get_pressed()
# handle left and right movement
if keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT]:
x_change = max(x_change-0.2, -max_speed)
elif keys[pygame.K_RIGHT] and not keys[pygame.K_LEFT]:
x_change = min(x_change+0.2, max_speed)
else:
x_change *= 0.98
# handle up and down movement
if keys[pygame.K_UP] and not keys[pygame.K_DOWN]:
y_change = max(y_change-0.2, -max_speed)
elif keys[pygame.K_DOWN] and not keys[pygame.K_UP]:
y_change = min(y_change+0.2, max_speed)
else:
y_change *= 0.98
x += x_change # Move the object.
y += y_change
display.fill(GRAY)
pygame.draw.rect(display, (0, 120, 250), (x, y, 20, 40))
pygame.display.update()
clock.tick(60)