To create an enemy in Godot, you build a scene that combines a visual (like a Sprite2D or AnimatedSprite2D), a collision shape (like a CollisionShape2D), and a script that controls its behavior. You then add movement, health, and interaction logic so the enemy can patrol, chase, take damage, and be defeated.
Setting Up the Enemy Scene
Start by creating a new scene with a root node of type CharacterBody2D (for 2D games) or CharacterBody3D (for 3D games). This node gives you built-in movement and collision detection. Add a Sprite2D (or AnimatedSprite2D) as a child to display the enemy, and a CollisionShape2D with a shape (like a rectangle or circle) that matches the enemy’s size. Save the scene as enemy.tscn.
For a simple enemy, you might also add a Timer node to control patrol intervals or a RayCast2D to detect walls and edges. These extra nodes help make the enemy behave more naturally.
Writing the Enemy Script
Attach a new script to the root node. The script will handle movement, health, and interactions. Here’s a basic structure:
extends CharacterBody2D
@export var speed = 100
@export var health = 3
func _physics_process(delta):
# Movement logic goes here
move_and_slide()
func take_damage(amount):
health -= amount
if health <= 0:
queue_free()
This script gives the enemy a speed, health, and a take_damage() function you can call from a player’s attack. The _physics_process() function is where you add movement—for example, moving left and right or chasing the player.
Adding Patrol Movement
To make the enemy patrol between two points, you can use a simple state variable. For example:
var direction = 1
func _physics_process(delta):
velocity.x = direction * speed
move_and_slide()
# Flip direction when hitting a wall
if is_on_wall():
direction *= -1
This makes the enemy move horizontally until it hits a wall, then reverse. For edge detection, add a RayCast2D pointing downward and check if it’s not colliding—if not, reverse direction. This prevents the enemy from walking off ledges.
Implementing Chase Behavior
To make the enemy chase the player, you need a reference to the player node. You can find it using get_node("/root/World/Player") or by using groups. In the script, calculate the direction to the player and move toward them:
@onready var player = get_node("/root/World/Player")
func _physics_process(delta):
var direction_to_player = (player.global_position - global_position).normalized()
velocity = direction_to_player * speed
move_and_slide()
This simple chase will follow the player directly. For more advanced behavior, you can add a detection range (using an Area2D) so the enemy only chases when the player is close.
Taking Damage and Dying
To let the player damage the enemy, you need a way to detect hits. One common method is to use an Area2D on the player’s attack (like a sword swing) and connect its body_entered signal. When the enemy enters the area, call take_damage() on the enemy’s script.
# In the player's attack script
func _on_attack_area_body_entered(body):
if body.has_method("take_damage"):
body.take_damage(1)
You can also add knockback by setting the enemy’s velocity in the take_damage() function. For death, you might play an animation, spawn a particle effect, or drop loot before calling queue_free().
Common Mistakes and Tips
- Forgetting to call
move_and_slide()– Without it, the character won’t move or collide properly. - Not setting collision layers – Make sure the enemy’s collision layer doesn’t collide with other enemies unless you want that.
- Using
_process()instead of_physics_process()– For movement, use_physics_process()to stay in sync with the physics engine. - Hardcoding player paths – Using
get_node()with an absolute path breaks if you move scenes. Use groups or signals instead.
Frequently Asked Questions
How do I make an enemy respawn?
To respawn an enemy, you can either re-instance the scene from a script or keep the enemy hidden and reset its position and health. The simplest way is to use a spawner node that creates a new enemy instance when needed.
How do I make an enemy shoot projectiles?
Create a separate projectile scene (like a Area2D with a sprite and a script). In the enemy’s script, use a Timer to spawn projectiles at the enemy’s position and set their direction toward the player.
How do I make a boss with multiple phases?
Use a state machine in the enemy’s script. Define states like ‘idle’, ‘attack’, ‘hurt’, and ‘dying’. Change states based on health thresholds or timers, and modify behavior accordingly.
How do I make the enemy not fall off platforms?
Add a RayCast2D pointing downward from the enemy’s edge. In the script, check if the ray is not colliding (meaning no ground ahead) and reverse direction.
How do I make the enemy ignore the player when far away?
Use an Area2D as a detection zone. Only start chasing when the player enters that area, and stop when they leave. You can also check the distance manually in the script.
Can I use an AnimatedSprite2D for a simple enemy?
Yes, add an AnimatedSprite2D node, create an animation with multiple frames, and play it in the script. You can also flip the sprite horizontally based on the movement direction.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Classic Sci-Fi Movies Inspired by Star Trek
- Idle Raspberry Pi Projects for Everyday Use
- Knowledge Management Principles: Key Concepts
- Better Apple Music Client: Was It Worth It?
- iCloud Pricing Plans: Costs & Tiers
- Qubes OS: 7 Reasons It’s Wrong for You