Overview
ThemovingImg class creates an image that moves around the screen and bounces off the edges. Similar to movingRect but uses an image instead of a solid color rectangle.
Constructor
Parameters
The pygame surface to which the image will be drawn.
Path to the image file to load and animate.
The initial position of the image.
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 image’s position, handles boundary collisions, and draws the image.- Checks if image hits horizontal boundaries (left/right edges)
- Reverses X velocity if collision detected
- Checks if image hits vertical boundaries (top/bottom edges)
- Reverses Y velocity if collision detected
- Updates position by adding speed vector
- Updates the rect object
- Blits the image to the surface
Attributes
image- The loaded pygame image surfacepos- Current position as vec2dspeed- Velocity vector as vec2dsize- Image dimensions as vec2drect- The pygame.Rect used for positioning and drawingsurfaceSize- Size of the surface for boundary detection
Usage Example
Fromgame.py:
Notes
- The image 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 - Image size is automatically determined from the loaded image
- Position and velocity are updated every frame when
draw()is called - Uses vec2d for 2D vector operations
- Images are loaded without
convert_alpha()unlike other image widgets