Maison  >  Article  >  développement back-end  >  feuille de sprite d'animation pygame

feuille de sprite d'animation pygame

WBOY
WBOYavant
2024-02-12 08:12:04625parcourir

feuille de sprite danimation pygame

Contenu de la question

Je souhaite créer un RPG descendant dans Pygame à l'aide de feuilles de sprite.

Par exemple, je veux pouvoir appuyer sur la barre d'espace pour attaquer, ce qui déclenchera l'animation d'attaque puis reviendra à la normale

import pygame
from pygame.locals import *

pygame.init()

image = pygame.image.load("sprite_sheet.png")

clock = pygame.time.Clock()

screen =  pygame.display.set_mode((400, 250))

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()

        self.current_animation = 0
        self.max_animation = 5

        self.animation_cooldown = 150
        self.last_animation = pygame.time.get_ticks()

        self.status = {"prev": "standing",
                       "now": "standing"}

    def animate_attack(self):
        time_now = pygame.time.get_ticks()

        if time_now - self.last_animation >= self.animation_cooldown:
            self.last_animation = pygame.time.get_ticks()
            if self.current_animation == self.max_animation:
                self.current_animation = 0

                joshua.status["now"] = joshua.status["prev"]
            else:
                self.current_animation += 1


joshua = Player()

while True:
    screen.fill(0)
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                joshua.status["prev"] = joshua.status["now"]
                joshua.status["now"] = "attacking"

    if joshua.status["now"] == "attacking":
        joshua.animate_attack()

    screen.blit(image, (0, 0), (joshua.current_animation * 64, 0, 64, 64))

    pygame.display.flip()

    clock.tick(60)

Le code ci-dessus est ce que j'ai. Si j'appuie une fois sur la barre d'espace, l'animation parcourt l'animation et s'arrête, mais si j'appuie deux fois sur la barre d'espace, elle boucle en raison de la façon dont elle est programmée.

Besoin d'aide avec les animations, merci


Bonne réponse


Le problème est causé par l'appel suivant lorsque l'on appuie une deuxième fois sur l'espace :

joshua.status["prev"] = joshua.status["now"]

Cela définira les statuts « Précédent » et « Maintenant » sur « Attaque ». En conséquence, lorsque l'état est réinitialisé dans la méthode animate_attack(), Il restera « Attaque » :

joshua.status["now"] = joshua.status["prev"]

En guise de solution rapide, assurez-vous de modifier le statut uniquement s'il n'a pas encore été défini :

if event.key == pygame.k_space:
    if not joshua.status["now"] == "attacking":
        joshua.status["prev"] = joshua.status["now"]
        joshua.status["now"] = "attacking"

Comme une meilleure solution, vous devriez encapsuler l'état, De cette façon, seule la classe du joueur peut gérer son propre état, par exemple :

class player():
    def __init__(self):
        self.current_animation = 0
        self.max_animation = 5
        self.animation_cooldown = 150
        self.last_animation = pygame.time.get_ticks()
        self.status = "standing" # simplified state

    def attack(self):
        self.status = "attacking"

    def animate_attack(self):
        if self.status == "attacking":
            time_now = pygame.time.get_ticks()
            if time_now - self.last_animation >= self.animation_cooldown:
                self.last_animation = pygame.time.get_ticks()
                if self.current_animation == self.max_animation:
                    self.current_animation = 0
                    self.status = "standing" # reset state
                else:
                    self.current_animation += 1

De cette façon, il n'est pas nécessaire de connaître un état en dehors de la classe :

while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                joshua.attack()

    joshua.animate_attack()

    screen.fill(0)
    screen.blit(image, (0, 0), (joshua.current_animation * 64, 0, 64, 64))
    pygame.display.flip()
    clock.tick(60)

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer