我正在做一个游戏,当玩家不断移动并处于中间位置时,背景会不断移动,以使其看起来好像玩家在移动。当我按两个箭头键时。向上和向右倾斜,但是当我放开向上箭头时,它应该继续向右移动。有时它可以工作,但大多数情况下只是停止运动。
我不知道该如何解决。
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[K_UP]:
if key[K_RIGHT]:
bg.move("up_right")
elif key[K_LEFT]:
bg.move("up_left")
else:
bg.move("up")
elif key[K_DOWN]:
if key[K_RIGHT]:
bg.move("down_right")
elif key[K_LEFT]:
bg.move("down_left")
else:
bg.move("down")
elif key[K_RIGHT]:
if key[K_DOWN]:
bg.move("down_right")
elif key[K_UP]:
bg.move("up_right")
else:
bg.move("right")
elif key[K_LEFT]:
if key[K_DOWN]:
bg.move("down_left")
elif key[K_UP]:
bg.move("up_left")
else:
bg.move("left")
这里的动作改变了
def move(self, direction):
if direction == "up_right":
self.posY += self.speed
self.posX -= self.speed
if direction == "up_left":
self.posY += self.speed
self.posX += self.speed
if direction == "down_right":
self.posY -= self.speed
self.posX -= self.speed
if direction == "down_left":
self.posY -= self.speed
self.posX += self.speed
if direction == "up":
self.posY += self.speed+2
if direction == "down":
self.posY -= self.speed+2
if direction == "right":
self.posX -= self.speed+2
if direction == "left":
self.posX += self.speed+2
起初,我没有添加“ up_left”等内容,因为我认为它只会通过两个ifs并在两个位置上进行编辑。但事实并非如此。
很抱歉,如果您已经找到了该主题的答案,但找不到任何答案。
谢谢
答案 0 :(得分:0)
您的主要问题是您检查事件循环中是否按下了键:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# only executed if there's an event returned by pygame.event.get()
# and possible executed multiple times per frame
key = pygame.key.get_pressed()
if key[K_UP]:
...
因此,仅当队列中当前有事件时,才执行执行移动(if key[K_UP]: ...
)的代码。
只需将此代码移到事件处理程序循环之外即可:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# always executed every frame
key = pygame.key.get_pressed()
if key[K_UP]:
...
恕我直言,处理运动的更好方法是使用向量,因为它们可以轻松确保恒定的运动速度,并且代码更少。
这是一个简单的例子:
import pygame
def main():
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
dt = 0
movement = {
pygame.K_UP: ( 0, -1),
pygame.K_DOWN: ( 0, 1),
pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: ( 1, 0)
}
pos = pygame.Vector2((100, 100))
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
pressed = pygame.key.get_pressed()
# calculate the movement vector
move = pygame.Vector2()
for dir in (movement[key] for key in movement if pressed[key]):
move += dir
if move.length() > 0: move.normalize_ip()
# ensure we have a constant speed
pos += move * dt/5
screen.fill(pygame.Color('grey'))
pygame.draw.circle(screen, pygame.Color('dodgerblue'), [int(x) for x in pos], 20, 0)
pygame.display.update()
dt = clock.tick(60)
if __name__ == '__main__':
main()