Jump to content

[ PT-BR / EN ] Create "Walk" / Universal LPC Spritesheet Generator


srunobantana

Recommended Posts

7c289ba3f2c794cfa517ca3d8708782f.png >>>>>>> 0c57a8d1ce6383a6a48bd2cf7a039c49.png


[PT] Vamos criar um personagem andando corretamente com o Universal LPC Spritesheet Generator. Geramos a imagem "Walk.png" e recortamos os frames automaticamente com um código em Python que eu desenvolvi.
[EN] Let's create a walking character correctly using theUniversal LPC Spritesheet Generator. We generate the "Walk.png" image and crop the frames automatically with a Python script I developed.


[PT] Para nĂŁo alongar o tutorial, vou ensinar apenas como recortar automaticamente a imagem "Walk.png", gerada pelo Universal LPC Spritesheet Generator, usando um cĂłdigo em Python que desenvolvi.
[EN] To keep this tutorial short, I'll show only how to automatically crop the "Walk.png" image, generated by the Universal LPC Spritesheet Generator, using a Python script I created.

b9629b842c0c546604f84df42243a7b1.png
 

[PT] Primeiro passo:

Crie seu personagem no Universal LPC Spritesheet Generator. NĂŁo vou ensinar a montar o modelo para deixar o tutorial mais objetivo. Solte sua imaginação — Ă© bem simples e prĂĄtico.

[EN] Step one:

Create your character using the Universal LPC Spritesheet Generator. I won’t cover how to design the model to keep this tutorial simple. Just use your creativity — it’s easy and intuitive.

 

[PT] Segundo passo:

Após finalizar seu personagem, clique em “Spritesheet split animation images, credits, JSON (zip)” para gerar o arquivo compactado.

[EN] Step two:

After finishing your character, click on “Spritesheet split animation images, credits, JSON (zip)” to generate the zipped file.

b99aae698d5de0cf706b8e5d144ff98b.png

 

[PT] Usando o WinRAR, extraia a pasta obtida pelo botão “Spritesheet split animation images, credits, JSON (zip)”.

Dentro dessa pasta, vocĂȘ encontrarĂĄ os seguintes arquivos:
backslash.png, climb.png, combat_idle.png, emote.png, halfslash.png, hurt.png, idle.png, jump.png, run.png, shoot.png, sit.png, slash.png, spellcast.png, thrust.png e "walk.png".

Por enquanto, o seu foco serĂĄ apenas no arquivo "walk.png".
Arraste esse arquivo para sua Área de Trabalho para facilitar o acesso.

[EN] Using WinRAR, extract the folder downloaded via the button “Spritesheet split animation images, credits, JSON (zip)”.

This folder contains the following files:
backslash.png, climb.png, combat_idle.png, emote.png, halfslash.png, hurt.png, idle.png, jump.png, run.png, shoot.png, sit.png, slash.png, spellcast.png, thrust.png, and "walk.png".

For now, focus only on the "walk.png" file.
Drag this file to your Desktop for easier access.


https://ascensiongamedev.com/resources/filehost/b31eeffcd645fa8b5fb0d6dc6821af53.mp4

 

[PT]🚀 Instalação – Etapa Final (90% Concluído!)

Agora estamos na etapa final, que pode parecer um pouco chata, mas fique tranquilo: vocĂȘ sĂł precisarĂĄ fazer isso uma Ășnica vez. Depois de configurado, nunca mais precisarĂĄ repetir o processo.

Para executar meu cĂłdigo, que foi desenvolvido em Python, Ă© necessĂĄrio instalar o Python na sua mĂĄquina. Mas nĂŁo se preocupe — Ă© muito mais simples do que parece!

[EN]🚀 Installation – Final Step (90% Completed!)

Now we are at the final step, which may seem a bit boring, but don’t worry: you’ll only need to do this once. After everything is set up, you won’t need to do it again.

To run my code, which was developed in Python, you need to install Python on your computer. But don’t worry — it’s much simpler than it sounds!
 

 

[PT] Instalar a Biblioteca Necessåria

Abra o Prompt de Comando (CMD) do Windows e digite o seguinte comando oficial do Python:

pip install pillow

📄 Caso queira, vocĂȘ pode acessar a documentação oficial do Python aqui.
 

[EN] Install the Required Library

Open the Windows Command Prompt (CMD) and type the following official Python  command:

pip install pillow

📄 If you want, you can access the official Pillow documentation here.

 

 

[PT]đŸ€” Perguntas Frequentes

Por que vocĂȘ nĂŁo envia o cĂłdigo jĂĄ em um executĂĄvel (.exe) para Windows, em vez do cĂłdigo fonte em Python?
đŸ”č Resposta: Eu atĂ© poderia gerar um arquivo walk.exe, porĂ©m existe um problema comum: quando criamos executĂĄveis de scripts em Python, alguns antivĂ­rus acusam como vĂ­rus ou ameaça, mesmo que o cĂłdigo seja totalmente seguro. Isso acontece porque a linguagem Python tambĂ©m Ă© utilizada por hackers para desenvolver scripts maliciosos — e, por precaução, os antivĂ­rus classificam como de "alto risco" qualquer arquivo compilado desse tipo.

Por esse motivo, prefiro manter o cĂłdigo em formato open source (cĂłdigo aberto). Assim, vocĂȘ pode simplesmente copiar o conteĂșdo, colar no Bloco de Notas, salvar com o nome: walk.py

E executar diretamente na sua mĂĄquina, de forma simples, transparente e segura.
 

[EN]đŸ€” Frequently Asked Questions (FAQ)

Why don’t you send the code already as an executable (.exe) for Windows instead of the Python source code?
đŸ”č Answer: I could generate a walk.exe file, but there’s a common problem: when we create executable files from Python scripts, some antivirus software will flag it as a virus or a threat — even if the code is completely safe. This happens because Python is also used by hackers to create malicious scripts, so as a precaution, antivirus programs often classify these executables as “high risk.”

For this reason, I prefer to keep the code in open-source format. This way, you can simply copy the content, paste it into Notepad, save it with the name: walk.py

And run it directly on your computer — in a simple, transparent, and safe way.

 

[PT]⚙ Executando o Script – Recorte AutomĂĄtico da Imagem

Após concluir a instalação do Python na sua måquina, faça o download do código que realizarå automaticamente o recorte da sua imagem "Walk.png".

🔗 Link do arquivo: Auto_Walk.py

💡 Observação: Se vocĂȘ nĂŁo se sentir confortĂĄvel em baixar o arquivo, por questĂŁo de segurança ou confiança, vocĂȘ mesmo pode criar manualmente o arquivo.

✔ Basta abrir o Bloco de Notas, criar um arquivo com o nome: Auto_Walk.py

 

E colar nele o seguinte cĂłdigo:


📜 Código:

Spoiler

 

from PIL import Image
import os
import sys

# ConfiguraçÔes / Settings
frame_patterns = {
    # [PT] PadrÔes de colunas para cada linha original (0-3)
    # Cada lista representa quais colunas (0-8) serĂŁo selecionadas para cada linha
    # Exemplo: Linha 0 usarĂĄ colunas 0, 3, 0, 7 (nessa ordem)
    # [EN] Column patterns for each original row (0-3)
    # Each list represents which columns (0-8) will be selected for each row
    # Example: Row 0 will use columns 0, 3, 0, 7 (in this order)
    0: [0, 3, 0, 7],
    1: [0, 1, 0, 5],
    2: [0, 3, 0, 7],
    3: [0, 1, 0, 5]
}

# [PT] Ordem final das linhas (reorganização vertical)
# [EN] Final row order (vertical reorganization)
final_line_order = [2, 1, 3, 0]

# [PT] NĂșmero de colunas e linhas na imagem original
# [EN] Number of columns and rows in the original image
frame_columns = 9
frame_rows = 4

def main():
    # [PT] Verifica permissÔes de leitura/escrita no diretório atual
    # [EN] Checks read/write permissions in current directory
    if not os.access('.', os.R_OK | os.W_OK):
        print("Erro: Sem permissĂŁo para ler/escrever no diretĂłrio atual.", file=sys.stderr)
        sys.exit(1)

    # [PT] Lista todos arquivos PNG no diretĂłrio
    # [EN] Lists all PNG files in the directory
    png_files = [f for f in os.listdir() if f.lower().endswith('.png')]
    if not png_files:
        print("Nenhum arquivo PNG encontrado no diretĂłrio atual.")
        return

    print(f"Encontrados {len(png_files)} arquivos PNG para processar.")

    for filename in png_files:
        try:
            print(f"\nProcessando {filename}...")
            
            # [PT] Tenta abrir a imagem
            # [EN] Attempts to open the image
            try:
                img = Image.open(filename)
            except Exception as e:
                print(f"Erro ao abrir {filename}: {e}", file=sys.stderr)
                continue

            # [PT] Valida se as dimensÔes são compatíveis com a grade definida
            # [EN] Validates if dimensions are compatible with defined grid
            if img.width % frame_columns != 0 or img.height % frame_rows != 0:
                print(f"Erro: {filename} não tem dimensÔes divisíveis por {frame_columns}x{frame_rows}.", file=sys.stderr)
                continue

            # [PT] Calcula tamanho de cada frame individual
            # [EN] Calculates size of each individual frame
            frame_width = img.width // frame_columns
            frame_height = img.height // frame_rows

            # [PT] Cria pasta de saĂ­da com nome Ășnico
            # [EN] Creates unique output folder
            base_name = os.path.splitext(filename)[0]
            output_folder = f"BySrunoBantana_{base_name}"
            
            if os.path.exists(output_folder):
                suffix = 1
                while os.path.exists(f"{output_folder}_{suffix}"):
                    suffix += 1
                output_folder = f"{output_folder}_{suffix}"
            
            os.makedirs(output_folder, exist_ok=True)

            # [PT] Cria imagem temporåria para reorganização
            # [EN] Creates temporary image for reorganization
            temp_img = Image.new('RGBA', (frame_width * 4, frame_height * 4))
            
            # [PT] Processa cada linha conforme frame_patterns
            # [EN] Processes each row according to frame_patterns
            for original_row in range(frame_rows):
                selected_columns = frame_patterns.get(original_row, [])
                if len(selected_columns) != 4:
                    print(f"Erro: PadrĂŁo invĂĄlido para linha {original_row}.", file=sys.stderr)
                    continue

                # [PT] Para cada coluna no padrĂŁo, copia o frame correspondente
                # [EN] For each column in pattern, copies corresponding frame
                for col_index, original_col in enumerate(selected_columns):
                    if original_col >= frame_columns:
                        print(f"Erro: Coluna {original_col} fora dos limites.", file=sys.stderr)
                        continue

                    left = original_col * frame_width
                    upper = original_row * frame_height
                    frame = img.crop((left, upper, left + frame_width, upper + frame_height))
                    temp_img.paste(frame, (col_index * frame_width, original_row * frame_height))

            # [PT] Reorganiza as linhas conforme final_line_order
            # [EN] Reorganizes rows according to final_line_order
            final_img = Image.new('RGBA', (frame_width * 4, frame_height * 4))
            for new_pos, original_row in enumerate(final_line_order):
                line = temp_img.crop((0, original_row * frame_height, frame_width * 4, (original_row + 1) * frame_height))
                final_img.paste(line, (0, new_pos * frame_height))

            # [PT] Salva a imagem final e um arquivo README
            # [EN] Saves final image and README file
            output_img = os.path.join(output_folder, f"{base_name}_reorganized.png")
            final_img.save(output_img)
            print(f"✔ Imagem salva em {output_img}")

            with open(os.path.join(output_folder, "README.txt"), 'w', encoding='utf-8') as f:
                f.write("✹ SrunoBantana ✹\n\nSiga-me no Instagram:\nhttps://www.instagram.com/srunobantana/\n\nObrigado pelo apoio! ❀\n")

        except Exception as e:
            print(f"Erro inesperado ao processar {filename}: {e}", file=sys.stderr)
            continue

    print("\n✅ Concluído!")

if __name__ == "__main__":
    main()

 

 

[EN]⚙ Running the Script – Automatic Image Cropping

After completing the Python installation on your computer, download the code that will automatically crop your image "Wal.png".

🔗 File link: Auto_Walk.py

💡 Note: If you don’t feel comfortable downloading the file — for safety or trust reasons — you can easily create the file yourself manually.

✔ Simply open Notepad, create a file named: Auto_Walk.py

 

And paste the following code into it:


📜 Code:
 

Spoiler

 

from PIL import Image
import os
import sys

# ConfiguraçÔes / Settings
frame_patterns = {
    # [PT] PadrÔes de colunas para cada linha original (0-3)
    # Cada lista representa quais colunas (0-8) serĂŁo selecionadas para cada linha
    # Exemplo: Linha 0 usarĂĄ colunas 0, 3, 0, 7 (nessa ordem)
    # [EN] Column patterns for each original row (0-3)
    # Each list represents which columns (0-8) will be selected for each row
    # Example: Row 0 will use columns 0, 3, 0, 7 (in this order)
    0: [0, 3, 0, 7],
    1: [0, 1, 0, 5],
    2: [0, 3, 0, 7],
    3: [0, 1, 0, 5]
}

# [PT] Ordem final das linhas (reorganização vertical)
# [EN] Final row order (vertical reorganization)
final_line_order = [2, 1, 3, 0]

# [PT] NĂșmero de colunas e linhas na imagem original
# [EN] Number of columns and rows in the original image
frame_columns = 9
frame_rows = 4

def main():
    # [PT] Verifica permissÔes de leitura/escrita no diretório atual
    # [EN] Checks read/write permissions in current directory
    if not os.access('.', os.R_OK | os.W_OK):
        print("Erro: Sem permissĂŁo para ler/escrever no diretĂłrio atual.", file=sys.stderr)
        sys.exit(1)

    # [PT] Lista todos arquivos PNG no diretĂłrio
    # [EN] Lists all PNG files in the directory
    png_files = [f for f in os.listdir() if f.lower().endswith('.png')]
    if not png_files:
        print("Nenhum arquivo PNG encontrado no diretĂłrio atual.")
        return

    print(f"Encontrados {len(png_files)} arquivos PNG para processar.")

    for filename in png_files:
        try:
            print(f"\nProcessando {filename}...")
            
            # [PT] Tenta abrir a imagem
            # [EN] Attempts to open the image
            try:
                img = Image.open(filename)
            except Exception as e:
                print(f"Erro ao abrir {filename}: {e}", file=sys.stderr)
                continue

            # [PT] Valida se as dimensÔes são compatíveis com a grade definida
            # [EN] Validates if dimensions are compatible with defined grid
            if img.width % frame_columns != 0 or img.height % frame_rows != 0:
                print(f"Erro: {filename} não tem dimensÔes divisíveis por {frame_columns}x{frame_rows}.", file=sys.stderr)
                continue

            # [PT] Calcula tamanho de cada frame individual
            # [EN] Calculates size of each individual frame
            frame_width = img.width // frame_columns
            frame_height = img.height // frame_rows

            # [PT] Cria pasta de saĂ­da com nome Ășnico
            # [EN] Creates unique output folder
            base_name = os.path.splitext(filename)[0]
            output_folder = f"BySrunoBantana_{base_name}"
            
            if os.path.exists(output_folder):
                suffix = 1
                while os.path.exists(f"{output_folder}_{suffix}"):
                    suffix += 1
                output_folder = f"{output_folder}_{suffix}"
            
            os.makedirs(output_folder, exist_ok=True)

            # [PT] Cria imagem temporåria para reorganização
            # [EN] Creates temporary image for reorganization
            temp_img = Image.new('RGBA', (frame_width * 4, frame_height * 4))
            
            # [PT] Processa cada linha conforme frame_patterns
            # [EN] Processes each row according to frame_patterns
            for original_row in range(frame_rows):
                selected_columns = frame_patterns.get(original_row, [])
                if len(selected_columns) != 4:
                    print(f"Erro: PadrĂŁo invĂĄlido para linha {original_row}.", file=sys.stderr)
                    continue

                # [PT] Para cada coluna no padrĂŁo, copia o frame correspondente
                # [EN] For each column in pattern, copies corresponding frame
                for col_index, original_col in enumerate(selected_columns):
                    if original_col >= frame_columns:
                        print(f"Erro: Coluna {original_col} fora dos limites.", file=sys.stderr)
                        continue

                    left = original_col * frame_width
                    upper = original_row * frame_height
                    frame = img.crop((left, upper, left + frame_width, upper + frame_height))
                    temp_img.paste(frame, (col_index * frame_width, original_row * frame_height))

            # [PT] Reorganiza as linhas conforme final_line_order
            # [EN] Reorganizes rows according to final_line_order
            final_img = Image.new('RGBA', (frame_width * 4, frame_height * 4))
            for new_pos, original_row in enumerate(final_line_order):
                line = temp_img.crop((0, original_row * frame_height, frame_width * 4, (original_row + 1) * frame_height))
                final_img.paste(line, (0, new_pos * frame_height))

            # [PT] Salva a imagem final e um arquivo README
            # [EN] Saves final image and README file
            output_img = os.path.join(output_folder, f"{base_name}_reorganized.png")
            final_img.save(output_img)
            print(f"✔ Imagem salva em {output_img}")

            with open(os.path.join(output_folder, "README.txt"), 'w', encoding='utf-8') as f:
                f.write("✹ SrunoBantana ✹\n\nSiga-me no Instagram:\nhttps://www.instagram.com/srunobantana/\n\nObrigado pelo apoio! ❀\n")

        except Exception as e:
            print(f"Erro inesperado ao processar {filename}: {e}", file=sys.stderr)
            continue

    print("\n✅ Concluído!")

if __name__ == "__main__":
    main()

 


[PT]🎯 Etapa Final – Executando o Script

Chegamos à etapa final! 🎉
A partir daqui, vocĂȘ nĂŁo precisarĂĄ mais repetir nenhum dos processos deste tutorial.

✔ Agora Ă© simples: pegue sua imagem chamada "Walk.png", coloque ela na mesma pasta onde estĂĄ o arquivo "Auto_Walk.py", e execute o script.

🔾 O script funcionará automaticamente, desde que a imagem "Walk.png" esteja na mesma pasta que o arquivo "Auto_Walk.py".

đŸ—‚ïž Exemplo de estrutura da pasta:

 

NomeDaPasta
├── Auto_Walk.py
└── Walk.png
 

[EN]🎯 Final Step – Running the Script

This is the final step! 🎉


From here, you won’t need to repeat any of the steps in this tutorial.

✔ It’s simple: take your image named "Walk.png", place it in the same folder where the file "Auto_Walk.py" is located, and run the script.

🔾 The script will work automatically as long as "Walk.png" is in the same folder as "Auto_Walk.py".

đŸ—‚ïž Example of folder structure:

 

FolderName

├── Auto_Walk.py

└── Walk.png

[PT] Vídeo mostrando como recortar automaticamente a imagem “walk.png”.
Siga os passos do vĂ­deo para que tudo funcione corretamente.
Em caso de dĂșvidas, me chame no Discord.


[EN] Video showing how to automatically crop the “walk.png” image.
Follow the steps in the video to make everything work correctly.
If you have any questions, feel free to contact me on Discord.
 

https://s3.us-east-2.amazonaws.com/ascensiongamedev/filehost/52eae037e3444928a5cbc5cdc8b3b0b4.mp4

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...