Python - ¿Como animar Sprites con orientación en PyGame?

 
Vista:
Imágen de perfil de Jesus
Val: 6
Ha disminuido su posición en 20 puestos en Python (en relación al último mes)
Gráfica de Python

¿Como animar Sprites con orientación en PyGame?

Publicado por Jesus (4 intervenciones) el 26/10/2017 23:38:20
Hola amigos, antes de nada ¡Quiero decir: Gracias por leer mi consulta!
Bueno amigos ya desde hace tiempo estoy programando con la librería PyGame y he avanzado mucho desde que comencé, creando pequeños juegos con fines didácticos.

Ya se animar sprites, usar spritesheets, lo que aún no logro es animarlos con orientación a la dirección hacia donde van.

¡Gracias por tu tiempo!

Si tienen alguna duda con mi código, no duden en contactarme
¡Eh aquí mi código!

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
# -----------------------------
# Clase Spritesheet
# -----------------------------
 
class Spritesheet(object):
	"""docstring for Spritesheet"""
	def __init__(self, filename, columns, rows):
		super(Spritesheet, self).__init__()
 
		self.image = pygame.image.load(filename).convert()
		self.rect = self.image.get_rect()
 
		self.columns = columns
		self.rows = rows
 
		self.size = self.image.get_size()
 
		self.width = self.size[0]
		self.height = self.size[1]
 
		self.quantity = (self.columns * self.rows)
		self.images_width = (self.width / self.columns)
		self.images_height = (self.height / self.columns)
		self.images = []
 
	def get_images(self):
		for y in range(self.columns):
			for x in range(self.rows):
				self.images.append(self.image.subsurface((self.images_width * x, self.images_height * y), (self.images_width, self.images_height)))
 
		return self.images


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
# -------------------
# Clase Player
# -------------------
 
class Player(pygame.sprite.Sprite):
    """docstring for Player"""
    def __init__(self, filename, columns, rows, x , y):
        super(Player, self).__init__()
 
        self.sheet = Spritesheet(filename, columns, rows)
        self.images = self.sheet.get_images()
 
        self.concurrent_image = 0
        self.image = self.images[self.concurrent_image]
 
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
 
        self.width = self.sheet.images_width
        self.height = self.sheet.images_height
 
        self.horizontal_speed = 0
        self.vertical_speed = 0
 
        self.directions = {'north': 0, 'south': 3, 'east': 2, 'west': 1}
        self.direction = 'south'
        self.moving = False
 
        self.time = 0
 
    def speed_up(self, x, y):
 
        if self.direction == 'north':
            self.vertical_speed = -y
 
        elif  self.direction == 'south':
            self.vertical_speed = +y
 
        if self.direction == 'east':
            self.horizontal_speed = +x
 
        elif self.direction == 'west':
            self.horizontal_speed = -x
 
    def update(self, surface_width, surface_height, time):
 
        if self.moving:
 
            if self.concurrent_image < self.sheet.columns:
                self.image = self.images[self.concurrent_image]
 
                self.time += time
 
                if self.time > 0.125:
                    self.concurrent_image += 1
                    self.time = 0
 
                self.rect.x += self.horizontal_speed
                self.rect.y += self.vertical_speed
            else:
                self.concurrent_image = 0
        else:
            self.concurrent_image = 0
 
            self.image = self.images[self.concurrent_image]


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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# ---------------------------
# Importacion de los módulos
# ---------------------------
 
import pygame
from pygame.locals import *
 
# --------------------
#     Constantes
# --------------------
 
BLANCO = (255, 255, 255)
 
FPS = 30
 
# --------------------------------------
# Funcion principal del juego
# --------------------------------------
 
def main():
	# Iniciar pygame:
    pygame.init()
 
 
    screen_width = 640
    screen_height = 480
 
    # Crear una ventana:
    screen = pygame.display.set_mode((screen_width, screen_height))
 
    # Asignar un titulo a la ventana:
    pygame.display.set_caption('Screen')
 
    player = Player('spritesheet.png', 4, 4, 32, 48)
 
    objectPLayer = pygame.sprite.GroupSingle()
    objectPLayer.add(player)
 
    # Variable para controlar el ciclo principal
    mainloop = True
 
    playtime = 0.0
    milliseconds = 0.0
 
    clock = pygame.time.Clock()
 
    # -------------------- Ciclo principal -------------------- #
    while mainloop:
        seconds = (milliseconds / 1000.0)
        playtime += seconds
 
    	# Obtiene todos los eventos de la lista de eventos
        for evt in pygame.event.get():
    		# Si el usuario presiona la [X]
            if evt.type == pygame.QUIT:
    			# Sale de ciclo principal
                mainloop = False
 
            if evt.type == pygame.KEYDOWN:
 
                if evt.key == pygame.K_UP:
                    player.speed_up(player.horizontal_speed, 4)
                    player.direction = 'north'
                    player.moving = True
 
                if evt.key == pygame.K_DOWN:
                    player.speed_up(player.horizontal_speed, 4)
                    player.direction = 'south'
                    player.moving = True
 
                if evt.key == pygame.K_LEFT:
                    player.speed_up(4, player.vertical_speed)
                    player.direction = 'west'
                    player.moving = True
 
                if evt.key == pygame.K_RIGHT:
                    player.speed_up(4, player.vertical_speed)
                    player.direction = 'east'
                    player.moving = True
 
            if evt.type == pygame.KEYUP:
 
                if evt.key == pygame.K_UP:
                    player.speed_up(player.horizontal_speed, 0)
                    player.moving = False
 
                if evt.key == pygame.K_DOWN:
                    player.speed_up(player.horizontal_speed, 0)
                    player.moving = False
 
                if evt.key == pygame.K_LEFT:
                    player.speed_up(0, player.vertical_speed)
                    player.moving = False
 
                if evt.key == pygame.K_RIGHT:
                    player.speed_up(0, player.vertical_speed)
                    player.moving = False
 
        screen.fill(BLANCO)
 
        objectPLayer.update(screen_width, screen_height, seconds)
        objectPLayer.draw(screen)
 
    	# Actualiza la ventana
        pygame.display.update()
 
    	# Coloca un limite de velocidad para FPS
        milliseconds = clock.tick(FPS)
 
    # Apaga pygame:
    pygame.quit()
 
if __name__ == "__main__":
    main()
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder