Skip to content Skip to sidebar Skip to footer

Valueerror: Subsurface Rectangle Outside Surface Area

I'm making an platformer game where the camera follows the player. I'm trying to implement this by having a large surface surface with the whole map and only blitting a zoomed in s

Solution 1:

Here is how i do my camera movement:

WINDOW_WIDTH, WINDOW_HEIGHT = ...
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), RESIZABLE)
screen = pygame.Surface(your_resolution)
...
scroll_x, scroll_y = player_position  # get the scroll
...
screen.blit(image, (x_pos + scroll_x, y_pos + scroll_y))
...
for event in pygame.event.get():
    if event.type == VIDEORESIZE:
        WINDOW_WIDTH, WINDOW_HEIGHT = event.size
...
window.blit(pygame.transform.scale(screen, (WINDOW_WIDTH, WINDOW_HEIGHT)), (0, 0))
pygame.display.update()

every time you want to show something you need to blit it onto screen instead of window.

if you want to have the same scale i would recommend the follwing class:

classWindow:
    def__init__(self, surf, width, height):
        self.screen = pygame.display.set_mode((width, height), RESIZABLE)
        self.surf = surf
        self.orig_w, self.orig_h = surf.get_size()
        self.set_sizes(width, height)

    defset_sizes(self, width, height):
        self.rate = min(width / self.orig_w, height / self.orig_h)
        self.width = int(self.orig_w * self.rate)
        self.x_off = int((width - self.width) / 2)
        self.height = int(self.orig_h * self.rate)
        self.y_off = int((height - self.height) / 2)

    defget_mouse_pos(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        returnint((mouse_x - self.x_off) / self.rate), int((mouse_y - self.y_off) / self.rate)

    defshow(self):
        self.screen.fill((50, 50, 50))
        self.screen.blit(pygame.transform.scale(self.surf, (self.width, self.height)), (self.x_off, self.y_off))
        pygame.display.flip()

EDIT: OPTIMTZING

the following code will replace the line that caused you problems: instead of

scaled = scaled.subsurface(...)
self.screen.blit(scaled, (0, 0))

do

self.screen.blit(scaled, (0, 0), self.fit_to_rect)

this is more efficient because it doesn't need to create the subsurface but blits is directly onto the screen. optimizing tips: avoid recreating surfaces every frame. your large surface does only need to be created when the map is loaded and never again. if you are rotating images you can simply create a list or dict of rotated images at the start of the program and just need to call it. same goes for changes in scale.

use img = img.convert() this is a pretty simple optimizing trick.

Post a Comment for "Valueerror: Subsurface Rectangle Outside Surface Area"