Subsurface rect outside of surface area when using get_clip() in Pygame?

帅比萌擦擦* 提交于 2021-02-10 14:50:20

问题


I am currently working on a pygame, trying to animate my character so that as the player moves him the program will cycle through four sprite image subsurfaces. I already setup a class for this:

import pygame
from pygame.locaks import *

class Prota:

    def __init__(self, sheet):
        self.sheet = pygame.image.load(sheet).convert_alpha()
        self.image_rect = self.sheet.get_rect()
        self.image_rect_h = (self.image_rect.height) #num of rows
        self.image_rect_w = (self.image_rect.width/16) #num of columns
        self.image_reel = self.fetch()
        self.image_cue = 0 #index: 0 - 3 (Right), 4 - 7 (Left), 8 - 11 (Front), 12 - 15 (Back)
        self.clock = pygame.time.Clock()

    def draw(self, screen):
        self.clock.tick(60)
        screen.blit(self.image_reel[self.image_cue], (400, 300))

    def fetch(self):
        sprites = []

        for x in range(0, 15):
            self.sheet.set_clip(pygame.Rect(self.image_rect_h*x, 0, self.image_rect_w, self.image_rect_h))
            sprite = self.sheet.subsurface(self.sheet.get_clip())
            sprites.append(sprite)
        return sprites

And it worked perfectly when I used a dummy sprite sheet (just a simple 50 x 50 square sprite that changes colors), but when I tried to implement my (partially complete) actually character sheet, I got back

ValueError: subsurface rectangle outside surface area

I am not sure if it's the size of sheets (the dummy sheet was 832 x 52px, and the character sheet is 1008 x 79px), or what, and I can't seem to find any article that addresses this issue. (The closest I could find in a quick search was How to rotate images in pygame

Any ideas?


回答1:


The mistake was to use self.image_rect_h*x as the first argument (the x-coord) of the pygame.Rect. Changing it to self.image_rect_w*x fixed it.

self.sheet.set_clip(pygame.Rect(self.image_rect_w*x, 0, self.image_rect_w, self.image_rect_h))

I'm not sure why the error occurs, because pygame.Surface.set_clip and .get_clip should be restricted to the surface area. You should post the full traceback (error message).

I actually think it would be better to let the program crash if something is wrong with the image loading and cutting, so that it's easier to find the error, otherwise you would get incorrect sprites anyway. So you could just use pygame.Surface.subsurface instead of set_clip andget_clip.

rect = (self.image_rect_w*x, 0, self.image_rect_w, self.image_rect_h)
sprite = self.sheet.subsurface(rect)


来源:https://stackoverflow.com/questions/43329169/subsurface-rect-outside-of-surface-area-when-using-get-clip-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!