Good day. I am using Python 3.6.5 and Pygame. You see, the thing is, that my Mario
sprite just keeps moving up even when it shouldn't. Here's the relevant code:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
my_change = -2.5
if pygame.key == pygame.KEYUP:
if event.key == pygame.K_UP:
my_change = 2.5
my += my_change
As I said, it just keeps on moving up, up, up, UP!
Is your logic correct - KEYDOWN is when the key is pressed and KEYUP when it is released - so you would need to set change to set the direction the K_UP is the up arrow and K_DOWN is the down arrow - so maybe try something more like
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
my_change = -2.5
if event.key == pygame.K_DOWN:
my_change = 2.5
my += my_change
change it to something like this,
running = True
while running:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
my_change -= 2.5
if event.key == pygame.K_DOWN:
my_change += 2.5
my += my_change
What you want is to add "gravity". You can have a look around stackoverflow and there will be hundreds of similar questions.
The basic idea is that gravity is always there, you don't just add it when the keys are pressed.
You didn't post your full code, so assuming that the check you're doing is in your main loop and that you're using a standard "+ direction is low" setting, then all you have to do is always add the movement towards the bottom and reverse it only when the button is pressed.
That means something like this (again, with no full code I'm guessing a bit):
my_change = 2.5
running = True
while running:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
my_change = -2.5
if event.key == pygame.KEYUP:
if event.key == pygame.K_UP:
my_change = 2.5
my += my_change
It'd probably help if you thought of your change
as the velocity
, so that if you give a positive velocity it will move down, if it's negative it will move up, and if it's 0 it will not move at all.
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.