-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsliding_image.py
More file actions
40 lines (35 loc) · 2.24 KB
/
Copy pathsliding_image.py
File metadata and controls
40 lines (35 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import pygame
# Class for repeateing sliding images
class SlidingImage:
def __init__(self, imagePath, position, speed=0, scale=1):
self.speed = speed
self.position = position
self.image = pygame.image.load(imagePath).convert()
self.image = pygame.transform.rotozoom(self.image, 0, scale) # rotzoom function prefered to scale due to filtering
self._width = self.image.get_width() # Storing the width so the get_width function doesn't need to be called repeatedly
self._offset = 0
self._calculate_repeats()
# Update the image offset and draw the duplciated + offset images to the screen
def update(self, surf, dt):
# update the offset
self._offset += self.speed * dt
absOffset = abs(self._offset)
if(absOffset >= self._width): # Loop the offset back around if it exceeds the width of the image
self._offset = absOffset%self._width * (-1 if self._offset < 0 else 1) # Ternary operator used for correct loop around of value
# Drawing the images on screen
for i in range(0,self._repeatsRight):
surf.blit(self.image, (self.position[0]+i*self._width+self._offset, self.position[1]))
for i in range(1,self._repeatsLeft): # we can skip the 0 index as it has been drawn in the loop above
surf.blit(self.image, (self.position[0]-i*self._width+self._offset, self.position[1]))
# The amount of times the image needs to be drawn to make the sliding seamless
# Repeat values calculated for both sides of the image for efficiency
def _calculate_repeats(self):
self._repeatsRight = (pygame.display.get_window_size()[0] - self.position[0])//self._width + 2
self._repeatsLeft = self.position[0]//self._width + 2
# available width // image width + 1 is enough for a stationary image to be displayed
# but a moving one requires an additional image in the row to not break the seamlessnes
# The position can be accessed directly from the outside using the position varibale
# But it should always be set using the set_position function due to the repeats needing to be recalculated
def set_position(self, position):
self.position = position
self._calculate_repeats()