반응형

스프라이트 애니메이션을 만들어 보자.

 

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import pygame
 
pygame.init()
pygame.display.set_caption("Super fun game development")
screen = pygame.display.set_mode((640480))
clock = pygame.time.Clock()
 
# 이미지 로드 함수.
def LoadImage(path, scale=None, colorkey=None):
    image = pygame.image.load(path).convert()
 
    if scale is not None:
        image = pygame.transform.scale(image, (image.get_width()*scale, image.get_height()*scale))
 
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((00))
        image.set_colorkey(colorkey)
 
    return image
 
# pygame.sprite.Sprite 클래스를 상속하는 클래스는 update()를 재정의하고 image, rect 속성을 가져야한다.
class Cat(pygame.sprite.Sprite):
    def __init__(self, position):
        #super(Cat, self).__init__()        
        pygame.sprite.Sprite.__init__(self)
 
        self.elapsedTime = 0
        self.limitTime = 1000/8
        # 1초에 한 사이클. Cat의 Run 동작은 8프레임이다.
        
        self.direction = 1
        self.speed = 4
        self.index = 0
        self.images = [
            LoadImage("Run1.png"0.5-1), LoadImage("Run2.png"0.5-1), LoadImage("Run3.png"0.5-1),
            LoadImage("Run4.png"0.5-1), LoadImage("Run5.png"0.5-1), LoadImage("Run6.png"0.5-1),
            LoadImage("Run7.png"0.5-1), LoadImage("Run8.png"0.5-1) ]
        self.image = self.images[self.index]
        self.rect = self.image.get_rect(center=position)
 
    def flip_image(self):
        self.images = [pygame.transform.flip(image, TrueFalsefor image in self.images]
        # list comprehension
 
    def update(self):
        # 1초에 8프레임 업데이트.
        self.elapsedTime += clock.get_time()
        if self.elapsedTime < self.limitTime:
            pass
        else:
            self.elapsedTime = 0
            self.index += 1
            if self.index >= len(self.images):
                self.index = 0
            self.image = self.images[self.index]
 
def main():
    cat = Cat(position=(screen.get_width()/2, screen.get_height()/2))
    #all_sprites = pygame.sprite.Group(cat)
    all_sprites = pygame.sprite.Group()
    # 스프라이트 오브젝트를 관리하기 위한 컨테이너 클래스
    all_sprites.add(cat)
    # 스프라이트를 삭제할 때는 all_sprites.remove(cat)
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            if cat.direction > 0:
                cat.flip_image()
                cat.direction = -1
            cat.rect.move_ip(-cat.speed, 0)
            
        if keys[pygame.K_RIGHT]:
            if cat.direction < 0:
                cat.flip_image()
                cat.direction = 1
            cat.rect.move_ip(cat.speed, 0)
 
        all_sprites.update()
        # 그룹에 속한 모든 스프라이트의 update()를 호출한다.
        
        screen.fill("blue")        
        all_sprites.draw(screen)
        # 그룹에 속한 모든 스프라이트의 image, rect 속성을 이용해 screen에 출력한다.
        # 그룹은 스프라이트의 순서(z-order)를 임의로 정한다.
        pygame.display.flip()
 
        clock.tick(60)
 
    pygame.quit()
 
if __name__ == '__main__':
   main()
 

 

Cat.zip
0.49MB

 

고양이가 자연스럽게 걷고있다.

 

※ 참고

Z-Order에 따라 스프라이트를 그려야 한다면 아래 링크를 확인하자.

LayeredUpdates

This group is fully compatible with pygame.sprite.Sprite.
You can set the default layer through kwargs using 'default_layer' and an integer for the layer. The default layer is 0.
If the sprite you add has an attribute _layer then that layer will be used. If the **kwarg contains 'layer' then the sprites passed will be added to that layer (overriding the sprite.layer attribute). If neither sprite has attribute layer nor **kwarg then the default layer is used to add the sprites.

 

반응형
Posted by J-sean
: