This tutorial explains the purpose and use of a Rect object in Pygame.

In every game, each object requires a set of fixed boundaries that define the space that it occupies. These fixed boundaries are essential when the object interacts or “collides” with other objects.

By defining these boundaries, the game is able to detect when two or more boundaries overlap or touch. This allows it to then handle the interact based on which objects are touching.

Common examples of this is when the Player’s sword collides the enemy, or when two Cars in a game collide or even a Player standing on the ground. These types of interactions are typically known as collision detection.


Rect objects

So what do Rect objects have to do with all this? Well, in Pygame we create “Rectangles” (short form Rect) around the objects we create in order to define it’s boundaries.

pygame rect

Can you guess where it’s boundaries are? See the pic below to find out.

Pygame rect example

And yes, there is some “white space” where the boundary exists, but the Car doesn’t. This is just an inaccuracy that we’ll have to live with in Pygame. Other advanced game engines (Unity/Unreal) use much more advanced techniques that completely take on the shape of the object.

Pygame is a really basic game library that only offers rectangle boundaries, and not others like for spheres or irregular shapes. This is why it’s only used for small projects.

This rectangle object has the same width and height as the Sprite itself and represents it’s boundaries.

This “rectangle” around the player is obviously a hidden (not visible) one and used for scenarios like collision detection. Pygame comes with several functions that can detect if two or more rect objects are intersecting with each other, otherwise known as a “collision”. The act of detecting these intersections is what is known as collision detection.


Creating a Rect

There are actually several ways to create Rects in Pygame. We’ll explore all the relevant ones here.

Using the Rect Class

The most basic way to create a Rect object in Pygame is to simply pass two tuples into the Pygame.Rect() Class. The first tuple (left, top) represents the position of the rect on the window, whereas the second tuple (width, height) represents the dimensions of the Rect.

object = pygame.Rect((20, 50), (50, 100))

The above code creates a rect at coordinates (20, 50) and of width 50 and height 100.

Creating a Rect using an Image

Here’s an example we picked out from one of our Pygame game tutorials. Usually we import an image for our Sprites like the Player Sprite in the below example.

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("Player_Sprite_R.png")
        self.rect = self.image.get_rect()

Instead of having to find out the dimensions of the image and creating a suitable rect object, you can just use the get_rect() function on the image object, automatically creating the appropriate rect dimensions.

Drawing the Rect to the Screen

Usually we use Rects just for collision detection, but sometimes we actually want to draw the Rectangle shape on screen. We can’t use the blit() function for this, rather we need to use the following method.

pygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60))

The above code draws a Rect of size (60, 60), to the (30, 30) position. The first parameter is the screen to which are are drawing to (usually called display or displaysurface. The second parameter is the color of the pygame rect.


Pygame Rect Functions

There are over a dozen different rectangle related functions in Pygame, so we won’t waste too much time on the not-so-common-or-important ones.

CollideRect

The CollideRect function is used to check whether two rect objects are intersecting / overlapping / colliding with each other (all terms are correct). Note, if only the boundaries (edges) are touching then False (0) will be returned.

import pygame

object1 = pygame.Rect((20, 50), (50, 100))
object2 = pygame.Rect((10, 10), (100, 100))
object3 = pygame.Rect((0, 0), (50, 50))

print(object1.colliderect(object2))
print(object1.colliderect(object3))
print(object2.colliderect(object3))

For any collisions that were detected, True (1) is returned otherwise False (0).

1
0
1

Using the above method on a rect object, you can determine whether it is in contact with the rect object that has been passed into it’s parameters. In simpler words, you can determine whether Sprite A is in contact with Sprite B.


Move

Another important function is the move() function which takes a set of X and Y coordinates to move the rectangle to, and then returns a new rect object.

object1 = pygame.Rect((20, 50), (50, 100))

object2 = object1.move(100, 100)
print(object1.topleft)
print(object2.topleft)
(20, 50)
(120, 150)

Alternatively, you can use the move_ip() function which means “move in place”. The only difference here is that instead of returning a new rect object with the new changes, it makes its changes directly to the rect object we are applying the function.

object1 = pygame.Rect((20, 50), (50, 100))

object1.move_ip(100, 100)
print(object1.topleft)
(120, 150)

The reason why use the topleft attribute is because pygame starts drawing from the topleft corner. So that’s the “beginning” of the shape in a way.


Other Rect Functions

collidepoint

Same as colliderect, but used to compare against a pair of coordinates instead of another rect object.

object1 = pygame.Rect((20, 50), (50, 100))
print(object1.collidepoint(50, 75))
1

collidelist

Collidelist is a function that compares a rect against a list of rect objects. If a collision against any rect in the list is detected, it’s index is returned.

object1 = pygame.Rect((20, 50), (50, 100))
object2 = pygame.Rect((10, 10), (100, 100))
object3 = pygame.Rect((0, 0), (50, 50))
object4 = pygame.Rect((100, 100), (30, 50))

list = [object4, object3, object2]
print(object1.collidelist(list))
2

Keep in mind that only the index of the first collision is returned.


rect update (NEW TO PYGAME 2.0)

Instead of individually accessing and updating each attribute of a rect, you can change them all at the same time with update() function. It’s an exact replica of the Rect class, requiring two tuples.

import pygame

object1 = pygame.Rect((20, 50), (50, 100))
object1.update((30, 30), (50, 50))
print(object1.topleft)
print(object1.size)
(30, 30)
(50, 50)

Rect objects attributes

A rect object in pygame has over a dozen attributes which tell you important information about it’s position and size.

We ran about half of them in the Python console to give you an idea how they work and what they return. You can also access and overwrite these values with your own ( e.g: object1.x = 20).

>>> object1.y
50
>>> object1.x
20
>>> object1.topright
(70, 50)
>>> object1.center
(45, 100)
>>> object1.size
(50, 100)
>>> object1.height
100
>>> object1.right
70
>>> object1.midright
(70, 100)
>>> object1.w
50

Here’s all the attributes that a rect object possesses.

x, y, top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, width, height, w, h

It’s a bit hard to actually learn much about these functions without actually seeing them being used practically. Unfortunately it’s rather how to show how they really work without atleast partially creating a game.

Here are some links to the some pygame game tutorial on our websites. If you’re interested you can learn more about rectangles and collision detection here.


This marks the end of the Pygame Rect Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments