How to make image move

Question:

So I have a image that I want to move by using the WASD keys. I do not fully understand how to do this, and I do have a main loop.
This is what my image looks like and it’s possition

no_image = pygame.image.load("Ideot.png").convert
x_coord = 500 
y_coord = 250
no_position = [x_coord,y_coord]

This code is behind the main loop. After the main loop I actually draw the image by doing

screen.blit(no_image,no_position)

This is what my loop looks like
done = False

while not done:
   for event in pygame == pygame.Quit:
       done = True

Can you show how to make the image move with WASD

Asked By: HALLOPEOPLE

||

Answers:

Getting an image to move while holding down a key is tricky. My preference is to use booleans.

If you do not have a tick method being used, STOP NOW and get one in place. Look at pygame.org/docs to see how to do it, they have great example code. Movement will not work as you want without it, because this loop will run as fast as your computer can process if you don’t limit it, so you may not even see your movement.

from pygame.locals import * # useful pygame variables are now at your disposle without typing pygame everywhere.

speed = (5, 5) # Amount of pixels to move every frame (loop).
moving_up = False
moving_right = False
moving_down = False
moving_left = False # Default starting, so there is no movement at first.

The above code is for OUTSIDE your while loop. Your event for loop will need to be changed slightly, to improve your code, I recommend putting functions into play here, or using dictionaries to rid the need of all these if statements but I won’t just for my answer being simpler and get the point across. I am leaving out some details, like event.quit, since you already have them.

If you don’t include the keyup part, your character will never stop moving!

for event in pygame.event.get():
    if event.type == KEYDOWN:
        if event.key == K_w:
            moving_up = True
        if event.key == K_d
            moving_right = True
        if event.key == K_s:
            moving_down = True
        if event.key == K_a:
            moving_left = True

    if event.type == KEYUP:
       if event.key == K_w:
            moving_up = False # .. repeat this for all 4.

Then later in the loop…

if moving_up:
    y_coord += -speed[1] # Negative speed, because positive y is down!
if moving_down:
    y_coord += speed[1]
if moving_right:
    x_coord += speed[0]
if moving_left:
    x_coord += -speed[0]

Now your x/y coordinates will change when they are set to move, which will be used to blit your image! Make sure you do NOT use elif in this scenario, if you are holding 2 keys, you want to be able to move by combining to keys, say right and up, so that you can move northeast.

Answered By: David Jay Brady
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.