How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame
In this article, we will learn how we can add moving platforms to our game using PyGame in Python.
Creating a Platform
We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function.
Syntax: pygame.draw.rect(surface, color, rect, width)
- surface : Here we can pass the surface on which we want to draw our rectangle.
- color : Here we can pass the color for our rectangle.
- rect : Here we can pass the rectangle, position, and dimensions.
- width : Here we can pass the line thickness. we can also create a solid rectangle by changing the value of this width parameter.
Moving the Platform
To move the platform we can create a velocity variable with some numeric value and we can add that velocity to the x coordinate of our platform. After that, we will multiply the velocity variable with -1 if its x coordinate is less than 100 or greater than or equal to 300.
Adding Player Sprite and Collision
Now we are going to add our player and collision between our player and platform. For this, we are using colliderect() method.
Syntax: pygame.Rect.colliderect(rect1 , rect2)
Parameters: It will take two rects as its parameters.
Returns true if any portion of either rectangle overlap.
If the player is colliding with the platform then we will set the coordinate of player bottom equal to the top of the platform and then we will add the platform velocity. We are also creating a gravity variable.