Creating movable objects
Creating non-movable objects
To start creating movable objects, you need to start with non-movable objects. We'll start of with a square. To create of square of length y and width x (ill use numbers) use the following line
# this will create a rectangle of RGB value (0, 128, 255) at position (30, 30) and of scale (60, 60)
pygame.draw.rect(gameDisplay, (0, 128, 255), pygame.Rect(30, 30, 60, 60))Adding keyboard input
Now we can get inputs from the user to make the square move. Add this code portion into the events loop. We'll add what action does later
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
#actionChanging the position of the square
Now that we can get keyboard input, let's add the code that changes the position of the square.
To change the position of the square now, you'll meed to change the values of two constantly changing variables. Lets define this variable before the loop that checks if the game is done
#setting initial position variables for the rectangle
rectX = 10
rectY = 10Now we set the position of the rectangle to those variables. Change the line defining the rectangle to the following
Now we have to change the variable values. I'll want to map moving to the arrow keys.
Because of the internal workings of pygame, the KEYDOWN event is defined by actually being pressed and not held. So to get the square moving we'll change the code to the following
Lastly, since the square is constantly being created we need to erase the square each frame. To do this, put this before the definition of then square
The final code should look like this
Last updated
Was this helpful?