pygame左右移动问题 [英] pygame moving left and right issue
问题描述
我已经开始在pygame上制作游戏,但是在向左或向右移动时遇到了问题。如果我迅速从按向右箭头键更改为按向左箭头键,然后又放开了向右箭头键,则该块停止移动。这是我的代码
I have started making something on pygame but I have encountered an issue when moving left or right. if I quickly change from pressing the right arrow key to pressing the left one and also let go of the right one the block just stops moving. this is my code
bg = "sky.jpg"
ms = "ms.png"
import pygame, sys
from pygame.locals import *
x,y = 0,0
movex,movey=0,0
pygame.init()
screen=pygame.display.set_mode((664,385),0,32)
background=pygame.image.load(bg).convert()
mouse_c=pygame.image.load(ms).convert_alpha()
m = 0
pygame.event.pump()
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
movex =-0.5
m = m + 1
if event.key==K_RIGHT:
movex=+0.5
m = m + 1
elif event.type == KEYUP:
if event.key==K_LEFT and not event.key==K_RIGHT:
movex = 0
if event.key==K_RIGHT and not event.key==K_LEFT:
movex =0
x+=movex
y=200
screen.blit(background, (0,0))
screen.blit(mouse_c,(x,y))
pygame.display.update()
有什么办法可以改变这个因此,如果按下向右箭头键并释放向左箭头键,它将向右移动而不是停止?
P.S
我仍在学习pygame,对本模块来说还是很新的东西。很抱歉,这似乎是一个愚蠢的问题,但我找不到任何答案。
is there a way I can change this so if the right arrow key is pressed and the left arrow key is released that it will go right instead of stopping? P.S I am still learning pygame and am very new to the module. I'm sorry if this seems like a stupid question but i couldn't find any answers to it.
推荐答案
您的问题是当您使用event.key == K_LEFT而不是event.key == K_RIGHT而不是event.key == K_RIGHT:$ b时,用$ p
Your problem is that when you test the KEYDOWN events with
if event.key==K_LEFT and not event.key==K_RIGHT:
您总是会得到True,因为当 event.key == K_LEFT
是True,
也总是 not event.key == K_RIGHT
(因为事件的键是 K_LEFT
毕竟。)
you always get True, because when event.key==K_LEFT
is True,
it also always is not event.key==K_RIGHT
(because the key of the event is K_LEFT
after all).
我对这类问题的处理方法是将
的意图与操作分开。因此,对于关键的
事件,我只是跟踪
应该发生什么动作,就像这样:
My approach to this kind of problem is to separate the intent from the action. So, for the key events, I would simply keep track of what action is supposed to happen, like this:
moveLeft = False
moveRight = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT: moveLeft = True
if event.key == K_RIGHT: moveRight = True
elif event.type == KEYUP:
if event.key == K_LEFT: moveLeft = False
if event.key == K_RIGHT: moveRight = False
然后,在循环的主要部分,您可以
根据输入采取行动,例如:
Then, in the "main" part of the loop, you can take action based on the input, such as:
while True:
for event in pygame.event.get():
...
if moveLeft : x -= 0.5
if moveRight : x += 0.5
这篇关于pygame左右移动问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!