.get_rect method.
When you use the .get_rect method on a loaded image, it returns two items: the current
coordinates of the image and the image’s size. By default, the image’s current coordinates on the game
surface are 0, 0. However, when you use the method, you can tell it where to place the image on the
game surface.
The size that the .get_rect method returns is the not the exact same size as the image. The method
assumes a rectangular shape around the image to obtain the size and position information. Thus,
.get_rect stands for “get the rectangle area around the image and return the rectangle’s current
position on the game screen.”
In the following example, the image used previously is used again as a Surface object. You can see
that a new variable, called GameImageLocation, is created, using the .get_rect method:
Click here to view code image
GameImage="/usr/share/raspberrypi-artwork/raspberry-pi-logo.png"
GameImageGraphic=pygame.image.load(GameImage).convert_alpha()
#
GameImageLocation=GameImageGraphic.get_rect()
To change the location of the image on the screen (that is, make it move), you use the .move method.
This method uses an offset to complete the “move” of the image. In essence, the script moves the
image so many pixels down and right on the game screen if the offset numbers are positive. If the
offset numbers are negative, the script moves the images up and left.
The following code sets the offset to [10, 10], which means it will move 10 pixels down and 10
pixels to the right:
Click here to view code image
# Set up Graphic Image Movement Speed #####
ImageOffset=[10,10]
#
#Move Image around
GameImageLocation=GameImageLocation.move(ImageOffset)
Often the offset is called speed because the higher the number, the higher the “speed” across the
screen.
Keep in the mind that the .move method does not redraw the image on the screen. You still need to
use the .blit method to redraw the image and python.display.update to redraw the
screen, as shown here:
Click here to view code image
GameScreen.fill(blue)
GameScreen.blit(GameImageGraphic,GameImageLocation)
pygame.display.update()
Notice that the .fill method is used before .blit draws the GameImageGraphic onto the
screen. Doing it this way “erases” all the previous images on the game screen and then redraws the
game image in its new location. This provides an illusion of the image moving.
Interacting with Graphics on the Game Screen
There are many ways to creatively interact with the graphics on the screen. Back in the “Staying in the