Logo de Godot Combat System

Godot Combat System

Comunidade
bgrenat
godot-combat-system

Expert patterns for combat systems including hitbox/hurtbox architecture, damage calculation (DamageData class), health components, combat state machines, combo systems, ability cooldowns, and damage popups. Use for action games, RPGs, or fighting games. Trigger keywords: Hitbox, Hurtbox, DamageData, HealthComponent, combat_state, combo_system, ability_cooldown, invincibility_frames, damage_popup.

Visão geral

Publicado porbgrenat
Repositóriogodot-game-dev-studio
Nome da habilidadegodot-combat-system
Estrelas
27
Forks
3
Arquivos incluídos
3
LicençaLGPL-3.0
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 3

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por bgrenat no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Godot Combat System no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/bgrenat/godot-game-dev-studio/tree/main/skills/godot-combat-system
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/bgrenat/godot-game-dev-studio.git /tmp/godot-game-dev-studio
mkdir -p .claude/skills
cp -r /tmp/godot-game-dev-studio/skills/godot-combat-system .claude/skills/godot-combat-system
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Godot Combat System em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Godot Combat System automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Godot Combat System não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Godot 4.7 Baseline

  • Expert patterns in this skill target Godot 4.7+ (stable, 2026-06-18).
  • Consult the Godot 4.7 migration guide when upgrading projects from 4.6.
  • NEVER assume 4.6 defaults (stretch mode, audio area_mask, RichTextLabel percent flags) without checking 4.7 migration notes.

Combat System

Expert guidance for building flexible, component-based combat systems.

NEVER Do

  • NEVER use direct damage references (target.health -= 10) — This bypasses armor, resistances, and invincibility logic. Always use a DamageData + HealthComponent pattern for consistent results.
  • NEVER forget invincibility frames (i-frames) — Without them, multi-hit attacks deal damage every single frame. Always apply a brief invincibility period (0.1–0.5s) after taking a hit.
  • NEVER keep hitboxes active permanently — This causes unintended "ghost" damage. Enable and disable hitboxes precisely using AnimationPlayer tracks or code-timed triggers.
  • NEVER use groups for physics-based hit filtering — Collision layers are evaluated in C++ and are significantly faster. Groups don't restrict physics intersections adequately for high-performance combat.
  • NEVER emit damage signals without a DamageData object — A raw number loses critical context like damage type, source, and knockback direction.
  • NEVER use try/catch blocks with validate targets — GDScript does not support exceptions. Use has_method(&"take_damage") or the is operator for safe type checking.
  • NEVER hardcode hitstun pauses using OS.delay_msec() — This blocks the entire OS thread and freezes the game. Use create_tween() or Engine.time_scale for visual hit-stop effects.
  • NEVER apply massive impulses to a RigidBody inside _process() — Physics-altering impulses must happen in _physics_process() or _integrate_forces() to remain deterministic and stable.
  • NEVER couple UI lifebars directly inside the Player script — Use a health_changed signal. This keeps your combat logic clean and independent of UI implementation details.
  • NEVER leave CollisionShapes active on dead entities — Corpses will block players and towers. Disable them immediately using set_deferred("disabled", true).
  • NEVER scale CollisionShapes non-uniformly — Non-uniform scaling breaks the physics engine's collision math. Always scale the internal resource (e.g., CircleShape2D.radius) instead.
  • NEVER use instanced Nodes for base stat data — Nodes carry unnecessary overhead. Use Godot's Resource class for lightweight, efficient, and inspectable stat containers.
  • NEVER use raw strings for elemental damage types — Strings are slow and error-prone. Use enum flags (optionally with @export_flags) to manage multi-type damage efficiently.
  • NEVER use standard strings for state names in high-frequency loops — Use StringName (&"attacking", &"stunned") to drastically improve dictionary lookups and hash comparison speeds.
  • NEVER forget to duplicate() a shared Resource stats block — If you don't call duplicate() when instancing a mob, all enemies of that type will share the same health pool.

Available Scripts

MANDATORY: Read the appropriate script before implementing the corresponding pattern.

combat_system_patterns.gd

10 Expert patterns: Safe duck-typing, hitstun tweens, nodeless AoE shape casting, and frame-perfect sync.

hitbox_hurtbox.gd

Component-based hitbox with hit-stop and knockback logic.


Damage System

gdscript
# damage_data.gd
class_name DamageData
extends RefCounted

var amount: float
var source: Node
var damage_type: String = "physical"
var knockback: Vector2 = Vector2.ZERO
var is_critical: bool = false

func _init(dmg: float, src: Node = null) -> void:
    amount = dmg
    source = src

Hurtbox/Hitbox Pattern

gdscript
# hurtbox.gd
extends Area2D
class_name Hurtbox

signal damage_received(data: DamageData)

@export var health_component: Node

func _ready() -> void:
    area_entered.connect(_on_area_entered)

func _on_area_entered(area: Area2D) -> void:
    if area is Hitbox:
        var damage := area.get_damage()
        damage_received.emit(damage)
        
        if health_component:
            health_component.take_damage(damage)
gdscript
# hitbox.gd
extends Area2D
class_name Hitbox

@export var damage: float = 10.0
@export var damage_type: String = "physical"
@export var knockback_force: float = 100.0
@export var owner_node: Node

func get_damage() -> DamageData:
    var data := DamageData.new(damage, owner_node)
    data.damage_type = damage_type
    
    # Calculate knockback direction
    if owner_node:
        var direction := (global_position - owner_node.global_position).normalized()
        data.knockback = direction * knockback_force
    
    return data

Health Component

gdscript
# health_component.gd
extends Node
class_name HealthComponent

signal health_changed(old_health: float, new_health: float)
signal died
signal healed(amount: float)

@export var max_health: float = 100.0
@export var current_health: float = 100.0
@export var invincible: bool = false

func take_damage(data: DamageData) -> void:
    if invincible:
        return
    
    var old_health := current_health
    current_health -= data.amount
    current_health = clampf(current_health, 0, max_health)
    
    health_changed.emit(old_health, current_health)
    
    if current_health <= 0:
        died.emit()

func heal(amount: float) -> void:
    var old_health := current_health
    current_health += amount
    current_health = minf(current_health, max_health)
    
    healed.emit(amount)
    health_changed.emit(old_health, current_health)

func is_dead() -> bool:
    return current_health <= 0

Combat State Machine

gdscript
# combat_state.gd
extends Node
class_name CombatState

enum State { IDLE, ATTACKING, BLOCKING, DODGING, STUNNED }

var current_state: State = State.IDLE
var can_act: bool = true

func enter_attack_state() -> bool:
    if not can_act:
        return false
    
    current_state = State.ATTACKING
    can_act = false
    return true

func enter_block_state() -> void:
    current_state = State.BLOCKING

func enter_dodge_state() -> bool:
    if not can_act:
        return false
    
    current_state = State.DODGING
    can_act = false
    return true

func exit_state() -> void:
    current_state = State.IDLE
    can_act = true

Combo System

gdscript
# combo_system.gd
extends Node
class_name ComboSystem

signal combo_executed(combo_name: String)

@export var combo_window: float = 0.5
var combo_buffer: Array[String] = []
var last_input_time: float = 0.0

func register_input(action: String) -> void:
    var current_time := Time.get_ticks_msec() / 1000.0
    
    if current_time - last_input_time > combo_window:
        combo_buffer.clear()
    
    combo_buffer.append(action)
    last_input_time = current_time
    
    check_combos()

func check_combos() -> void:
    # Light → Light → Heavy = Special Attack
    if combo_buffer.size() >= 3:
        var last_three := combo_buffer.slice(-3)
        if last_three == ["light", "light", "heavy"]:
            execute_combo("special_attack")
            combo_buffer.clear()

func execute_combo(combo_name: String) -> void:
    combo_executed.emit(combo_name)

Ability System

gdscript
# ability.gd
class_name Ability
extends Resource

@export var ability_name: String
@export var cooldown: float = 1.0
@export var damage: float = 25.0
@export var range: float = 100.0
@export var animation: String

var is_on_cooldown: bool = false

func can_use() -> bool:
    return not is_on_cooldown

func use(caster: Node) -> void:
    if not can_use():
        return
    
    is_on_cooldown = true
    
    # Execute ability logic
    _execute(caster)
    
    # Start cooldown
    await caster.get_tree().create_timer(cooldown).timeout
    is_on_cooldown = false

func _execute(caster: Node) -> void:
    # Override in derived abilities
    pass

Damage Popups

gdscript
# damage_popup.gd
extends Label

func show_damage(amount: float, is_crit: bool = false) -> void:
    text = str(int(amount))
    
    if is_crit:
        modulate = Color.RED
        scale = Vector2(1.5, 1.5)
    
    var tween := create_tween()
    tween.set_parallel(true)
    tween.tween_property(self, "position:y", position.y - 50, 1.0)
    tween.tween_property(self, "modulate:a", 0.0, 1.0)
    tween.finished.connect(queue_free)

Critical Hits

gdscript
func calculate_damage(base_damage: float, crit_chance: float = 0.1) -> DamageData:
    var data := DamageData.new(base_damage)
    
    if randf() < crit_chance:
        data.is_critical = true
        data.amount *= 2.0
    
    return data

Best Practices

  1. Separate Concerns - Health ≠ Combat ≠ Movement
  2. Use Signals - Decouple systems
  3. Area2D for Hitboxes - Built-in collision detection
  4. Invincibility Frames - Prevent spam damage

Elite Godot 4.x Patterns

1. Combat Logging & Telemetry

Use FileAccess and JSON to record combat events to the user:// directory for balancing analytics.

gdscript
# combat_logger.gd
class_name CombatLogger extends Node

const LOG_FILE := "user://combat_log.json"
var _session_log: Array[Dictionary] = []

func log_damage_event(source: String, target: String, amount: int) -> void:
    var event := { "source": source, "target": target, "damage": amount }
    _session_log.append(event)
    # Optimization: Batch flushes instead of writing on every event
    if _session_log.size() >= 10: _flush_to_disk()

func _flush_to_disk() -> void:
    var file := FileAccess.open(LOG_FILE, FileAccess.WRITE)
    if file:
        file.store_string(JSON.stringify(_session_log))
        file.close()

2. Authoritative Networked Damage

Clients should never dictate damage. Instead, they request a hit validation from the server via RPC, providing the target's node path and intended damage.

gdscript
# networked_damage_manager.gd
class_name NetworkedDamageManager extends Node

func request_damage(target: Node, amount: int) -> void:
    if multiplayer.has_multiplayer_peer():
        rpc_id(1, "server_validate_hit", target.get_path(), amount)

@rpc("any_peer", "call_remote", "reliable")
func server_validate_hit(target_path: NodePath, amount: int) -> void:
    var sender_id := multiplayer.get_remote_sender_id()
    var target_node := get_node_or_null(target_path)
    
    if is_instance_valid(target_node) and target_node.has_method("take_damage"):
        # Elite: Insert manual lag-compensation / distance checks here
        target_node.take_damage(amount)
        rpc_id(sender_id, "client_confirm_hit", target_path, amount)

@rpc("authority", "call_remote", "reliable")
func client_confirm_hit(target_path: NodePath, amount: int) -> void:
    print_rich("[color=green]Hit confirmed by server.[/color]")

3. Hitbox Visualizer (In-Game Debugging)

Toggle global collision visibility during live gameplay using SceneTree.debug_collisions_hint.

gdscript
# hitbox_visualizer.gd
class_name HitboxVisualizer extends Node

func toggle_debug_hitboxes() -> void:
    get_tree().debug_collisions_hint = not get_tree().debug_collisions_hint

## Set specific debug colors for different combat volumes
static func set_hitbox_color(shape: CollisionShape3D, is_attack: bool) -> void:
    shape.debug_color = Color.RED if is_attack else Color.GREEN

Reference

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Godot Combat System faz?

Expert patterns for combat systems including hitbox/hurtbox architecture, damage calculation (DamageData class), health components, combat state machines, combo systems, ability cooldowns, and damage popups. Use for action games, RPGs, or fighting games. Trigger keywords: Hitbox, Hurtbox, DamageData, HealthComponent, combat_state, combo_system, ability_cooldown, invincibility_frames, damage_popup.

Por que usar Godot Combat System no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Godot Combat System é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Godot Combat System no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/bgrenat/godot-game-dev-studio/tree/main/skills/godot-combat-system. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Godot Combat System?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Godot Combat System?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Godot Combat System com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Godot Combat System é gratuita?

Sim. A habilidade é publicada no GitHub por bgrenat sob a licença LGPL-3.0. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇