I have a strange behavior with when using pygame.
[...]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
[...]
while running:
[...]
dt = (new_time - start_time).total_seconds()
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
bot.brake(dt)
elif keys[pygame.K_UP]:
bot.accelerate(dt)
Sometimes, even if I am not pushing any key, it instantaneously starts to accelerate the bot. When I debug, I found that the key is pressed for pygames, even if I don't touch the keyboard. That happens even on a fresh start of the game.
Can you help me find the cause of this problem?
You may be able to use variables to manupulate and figure out what keys you're pressing. Though I like detecting Keypress in another function.
[...]
var MD,MU=False,False,False
[...]
def check():
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_DOWN:
MD=True
if event.key==pygame.K_UP:
MU=True
elif event.type==pygame.KEYUP:
elif event.key==pygame.K_UP:
MU=False
elif event.key==pygame.K_DOWN:
MD=False
Now you have to create a function to control you player.
def controlPlayer():
if MU:
#do what you want when up button is pressed
if MD:
#do what you want when down button is pressed
Then you implement both of these functions into the "While running" script
while running:
check()
controlPlayer()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.