2017-11-02 2 views
3

스프라이트에 모양을 그리는 대신 이미지를 스프라이트에로드하려면 어떻게해야합니까? 예 : I는 50 × 50의 RECT 여기파이 게임 - 스프라이트에 이미지로드

그리기의 스프라이트로 50 × 50 이미지를 대신로드하는 것은 지금까지 내 스프라이트 코드 :

class Player(pygame.sprite.Sprite): 

    def __init__(self, color, width, height): 

     super().__init__() 
     #Config 
     self.image = pygame.Surface([width, height]) 
     self.image.fill(WHITE) 
     self.image.set_colorkey(WHITE) 

      # Draw 
     pygame.draw.rect(self.image, color , [0, 0, width, height]) 

     # Fetch 
     self.rect = self.image.get_rect() 

    def right(self, pixels): 
     self.rect.x += pixels 
    def left(self, pixels): 
     self.rect.x -= pixels 
    def up(self, pixels): 
     self.rect.y -= pixels 
    def down(self, pixels): 
     self.rect.y += pixels 

답변

3

먼저 load 전역에서 또는 별도의 모듈에서 이미지와 그것을 가져 오십시오. __init__ 메서드에서로드하지 마십시오. 그렇지 않으면 인스턴스를 만들 때마다 하드 디스크에서 읽어야하며 속도가 느립니다.

이제 세계 IMAGE을 클래스 (self.image = IMAGE)에 할당 할 수 있으며 모든 인스턴스에서이 이미지를 참조합니다.

import pygame as pg 


pg.init() 
# The screen/display has to be initialized before you can load an image. 
screen = pg.display.set_mode((640, 480)) 

IMAGE = pg.image.load('an_image.png').convert_alpha() 


class Player(pg.sprite.Sprite): 

    def __init__(self, pos): 
     super().__init__() 
     self.image = IMAGE 
     self.rect = self.image.get_rect(center=pos) 

같은 클래스에 대해 서로 다른 이미지를 사용하려는 경우, 당신은 인스턴스화 중에 전달할 수 있습니다

class Player(pg.sprite.Sprite): 

    def __init__(self, pos, image): 
     super().__init__() 
     self.image = image 
     self.rect = self.image.get_rect(center=pos) 


player1 = Player((100, 300), IMAGE1) 
player2 = Player((300, 300), IMAGE2) 

convert 또는 convert_alpha 메소드 (투명도 이미지)를 사용하여 블리트 성능을 향상시킵니다.


이미지 (예를 들어, "이미지")의 하위 디렉토리에있는 경우, os.path.join와 경로 구성 : 나는 모든 것을 복사

import os.path 
import pygame as pg 

IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha() 
+0

및 이미지 따라서 스프라이트 그냥 표시, 표시되지 않습니다 비어 있습니다. – SnivyDroid

+0

Nvm 난 일할 수있어, 내가 colorkey 및 surface.fill 코드 블록을 제거 할 필요가 작동하도록, 감사합니다! – SnivyDroid