Overview
ThemovingRect class creates a colored rectangle that moves around the screen, bouncing off the edges. It supports velocity, gravity, and automatic boundary collision.
Constructor
Parameters
The pygame surface to which the rectangle will be drawn.
The initial position of the rectangle.
The width and height of the rectangle.
RGB color tuple for the rectangle (default is red).
The velocity vector (x, y) indicating movement speed and direction per frame.
Gravity value (parameter defined but not currently implemented in draw method).
Methods
draw()
Updates the rectangle’s position, handles boundary collisions, and draws the rectangle.- Checks if rectangle hits horizontal boundaries (left/right edges)
- Reverses X velocity if collision detected
- Checks if rectangle hits vertical boundaries (top/bottom edges)
- Reverses Y velocity if collision detected
- Updates position by adding speed vector
- Updates the rect object
- Draws the rectangle to the surface
Attributes
pos- Current position as vec2dsize- Dimensions as vec2dspeed- Velocity vector as vec2dcolor- RGB color tuplerect- The pygame.Rect used for drawingsurfaceSize- Size of the surface for boundary detection
Usage Example
Fromgame.py:
Notes
- The rectangle automatically bounces when it hits any screen edge
- Velocity reversal creates a “bounce” effect
- The
gravityparameter is defined but not currently implemented in the movement logic - Default size is 20x20 pixels
- Default color is red (255, 0, 0)
- Position and velocity are updated every frame when
draw()is called - Uses vec2d for 2D vector operations