Guide · Godot 4 · 2D enemies
How to make a slime enemy in Godot 4 (with free animated 16x16 sprites)
Short answer: in Godot 4, a slime enemy is a CharacterBody2D with an AnimatedSprite2D whose SpriteFrames are built from horizontal sprite-sheet strips (Add frames from a Sprite Sheet, Horizontal = frame count, Vertical = 1), plus two RayCast2D nodes for walls and ledges and an Area2D hitbox that damages the player. A small GDScript state machine (IDLE, HOP, HURT, DEAD) sets velocity, calls move_and_slide(), flips the sprite with flip_h, and frees the node with queue_free() when the non-looping death animation emits animation_finished. The complete scene and script are below and work in Godot 4.2 and later.
A slime is the classic first enemy: one sprite, simple movement, and it teaches everything you need for every other enemy (animation, physics, hit detection, death). If you are spending a long weekend or the holiday break finishing a small platformer, this is a good one-evening task. By the end you will have a slime that patrols, notices the player, hops toward them, refuses to jump off cliffs, flashes when hit, and pops when it dies.
The sprites (and where to get some)
This tutorial uses the free Animated Slime Enemies Pack from Slime Forge, but any sprite sheet laid out the same way works. The pack has 8 colours (green, red, blue, gold, ice, pink, purple, shadow), 16×16 frames, and one horizontal PNG strip per animation, for example slimes/green/green_idle.png and slimes/green/green_hop.png. A small .json next to each strip gives the frame count and speed:
Shortcut (pack v1.1+): the pack now also ships a ready-made godot/<colour>_spriteframes.tres for every colour. Copy the pack folder to res://slime_forge/ and assign that file to the AnimatedSprite2D to skip the slicing in step 2. To build such a file for your own sheets, see Godot 4 SpriteFrames from a sprite sheet.
| Animation | File | Frames | FPS | Loop |
|---|---|---|---|---|
| idle | green_idle.png | 4 | 6 | On |
| hop | green_hop.png | 6 | 10 | On |
| hurt | green_hurt.png | 2 | 8 | Off (plays once) |
| death | green_death.png | 5 | 10 | Off (plays once) |
In every frame the slime's feet sit on the bottom row of pixels, which matters when you line the sprite up with the collision shape. There is also a combined sheet per colour (green_all.png, 6 columns × 4 rows) if you prefer a single texture.
Where to get slime sprites
- Free: the Slime Forge pack (also on itch.io; usable in commercial games, credit appreciated but not required). itch.io and OpenGameArt also have many other free slime sprites; check each licence (CC0, CC-BY or custom) and whether it includes hurt and death frames, which many small packs leave out.
- Draw your own: a 16×16 slime is a good first pixel-art animation. Four idle frames of squash and stretch is enough to make it feel alive.
- More animations: Slime Forge DELUXE (4 €) adds 16 colours, attack, spawn, projectile and splash animations, and a 32×32 King Slime boss. It is optional; the attack section shows how to use those extra animations if you have them.
- More colours for free: recolour any slime with the Palette Swapper browser tool; the palette swap guide explains how to pick colours that keep the shading readable.
Want to skip the build? The free Godot 4 slime enemy asset (MIT) contains the finished result of this tutorial: 20 slime variants with SpriteFrames and a SlimeEnemy scene with patrol, ledge detection, contact damage, knockback and death.
Project setup for pixel art
- Copy the sprite folder into your project, for example
res://assets/slimes/. - Open Project > Project Settings > Rendering > Textures and set Canvas Textures > Default Texture Filter to Nearest. Without this, Godot 4 smooths your 16×16 pixels into a blur.
- Optional but recommended for a pixel-art game: in Display > Window set the viewport size small (for example 320×180), turn on Advanced Settings to set a Window Width/Height Override such as 1280×720, and set Stretch > Mode to
viewport. Godot 4.2+ also offers Stretch > Scale Mode = integer, which keeps every pixel the same size. - Select a PNG in the FileSystem dock and check the Import dock: Compress > Mode should be
Losslessand mipmaps off (the default for 2D textures). Click Reimport if you change anything. - Name your physics layers in Layer Names > 2D Physics: layer 1
world, layer 2player, layer 3enemies. Named layers make the collision settings below much easier to read.
Import the sprite sheets into AnimatedSprite2D
AnimatedSprite2D plays animations stored in a SpriteFrames resource. Each animation is a list of frames plus a speed and a loop flag.
- Create a new scene, add an
AnimatedSprite2Dnode (you will move it under the slime body in the next section). - In the Inspector, click Sprite Frames > [empty] > New SpriteFrames, then click the new resource. The SpriteFrames panel opens at the bottom of the editor.
- On the left, there is one animation called
default. Double-click it and rename itidle. - Click the Add frames from a Sprite Sheet button (the grid icon in the frames toolbar) and choose
green_idle.png. - In the Select Frames window, set Horizontal = 4 and Vertical = 1. The sheet is split into four 16×16 cells. Click each cell (or use the select-all button) and press Add 4 Frame(s).
- Set the animation speed field (FPS) to
6. Leave the Animation Looping toggle on. - Click Add Animation, name it
hop, and repeat withgreen_hop.png: Horizontal = 6, Vertical = 1, FPS 10, loop on. - Add
hurt(green_hurt.png, Horizontal = 2, FPS 8) anddeath(green_death.png, Horizontal = 5, FPS 10). For these two, turn Animation Looping off. This is essential: only non-looping animations emitanimation_finished. - Optionally select
idleand click Autoplay on Load so the editor preview animates. The script plays animations itself, so this is cosmetic. - Click the Sprite Frames resource's dropdown and choose Save As…, for example
res://enemies/slime/green_slime_frames.tres. Saving it separately lets you make other colours by duplicating the file and swapping the textures.
Using the combined sheet instead: pick green_all.png, set Horizontal = 6 and Vertical = 4, and add only the cells of the row you need (row 1 idle: 4 cells, row 2 hop: 6, row 3 hurt: 2, row 4 death: 5). Empty cells at the end of short rows must not be added, or the animation will blink.
Build the slime scene (node tree)
Make a new scene with this tree and save it as res://enemies/slime/slime.tscn:
Slime (CharacterBody2D) slime.gd, layer 3 "enemies", mask 1 "world"
├── AnimatedSprite2D sprite_frames = green_slime_frames.tres, offset (0, -8)
├── CollisionShape2D RectangleShape2D 12 x 9, position (0, -4.5)
├── Facing (Node2D) flipped with scale.x = -1 / 1
│ ├── FloorRay (RayCast2D) position (20, -4), target_position (0, 12), mask 1
│ └── WallRay (RayCast2D) position (0, -6), target_position (12, 0), mask 1
└── Hitbox (Area2D) layer none, mask 2 "player"
└── CollisionShape2D RectangleShape2D 10 x 8, position (0, -5)
- Origin at the feet. A centred 16×16 sprite extends 8 px below its node. With Offset = (0, -8) the bottom row of the art (the feet) sits exactly on the node's origin. The collision rectangle is also placed so its bottom edge is at
y = 0. Now the slime's position is its feet, which makes placing slimes on tiles trivial. - FloorRay sits ahead of the slime, roughly where it will land after one hop, and points down. If it hits nothing, there is a ledge ahead.
- WallRay points forward at body height. If it hits something, there is a wall.
- Facing holds both rays so that flipping one node (
scale.x = -1) flips both rays to the left. - Hitbox only looks at layer 2, so it detects the player and nothing else. It does not need a layer of its own.
- Leave the CharacterBody2D's Motion Mode on
Grounded(the default for platformers).
The full slime script (GDScript 2.0)
Attach this script to the Slime root node. It uses Godot 4 syntax only (@export, @onready, typed variables, the velocity property and move_and_slide() with no arguments).
extends CharacterBody2D
## Hopping slime: patrols, hops toward the player, takes damage and dies.
enum State { IDLE, HOP, HURT, DEAD }
@export var max_health: int = 3
@export var hop_speed: float = 60.0 # horizontal speed during a hop (px/s)
@export var hop_force: float = 180.0 # upward speed at take-off (px/s)
@export var idle_time: float = 0.8 # pause between hops (s)
@export var detect_range: float = 96.0 # chase the player when this close (px)
@export var contact_damage: int = 1
@export var knockback: float = 90.0
@export var friction: float = 600.0
var state: State = State.IDLE
var health: int
var direction: float = -1.0 # -1 = left, 1 = right
var _idle_left: float = 0.0
var _left_ground: bool = false
var _flash_tween: Tween
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var facing: Node2D = $Facing
@onready var floor_ray: RayCast2D = $Facing/FloorRay
@onready var wall_ray: RayCast2D = $Facing/WallRay
@onready var hitbox: Area2D = $Hitbox
func _ready() -> void:
health = max_health
add_to_group("enemies")
sprite.animation_finished.connect(_on_animation_finished)
hitbox.body_entered.connect(_on_hitbox_body_entered)
_set_facing(direction)
_enter_idle()
func _physics_process(delta: float) -> void:
if not is_on_floor():
velocity.y += gravity * delta # Godot 4.3+: velocity += get_gravity() * delta
match state:
State.IDLE:
velocity.x = move_toward(velocity.x, 0.0, friction * delta)
_idle_left -= delta
if _idle_left <= 0.0 and is_on_floor():
_try_hop()
State.HOP:
pass # keep the take-off velocity in the air
State.HURT, State.DEAD:
velocity.x = move_toward(velocity.x, 0.0, friction * delta)
move_and_slide()
# Landing check: must have left the floor first, then touch it again.
if state == State.HOP:
if not is_on_floor():
_left_ground = true
elif _left_ground:
_enter_idle()
# ---------- movement ----------
func _try_hop() -> void:
var chasing := false
var player := get_tree().get_first_node_in_group("player") as Node2D
if player and global_position.distance_to(player.global_position) <= detect_range:
chasing = true
var dx := player.global_position.x - global_position.x
if absf(dx) > 2.0:
direction = signf(dx)
_set_facing(direction)
if _is_blocked():
if chasing:
_enter_idle() # don't follow the player off a cliff: wait
return
direction = -direction # patrolling: turn around
_set_facing(direction)
if _is_blocked(): # blocked on both sides
_enter_idle()
return
state = State.HOP
_left_ground = false
velocity = Vector2(direction * hop_speed, -hop_force)
sprite.play("hop")
func _enter_idle() -> void:
state = State.IDLE
_idle_left = idle_time
sprite.play("idle")
func _set_facing(dir: float) -> void:
facing.scale.x = dir
sprite.flip_h = dir < 0.0 # assumes the art faces right
floor_ray.force_raycast_update()
wall_ray.force_raycast_update()
func _is_blocked() -> bool:
return wall_ray.is_colliding() or not floor_ray.is_colliding()
# ---------- damage ----------
func take_damage(amount: int, from_position: Vector2) -> void:
if state == State.DEAD:
return
health -= amount
_flash()
var push := signf(global_position.x - from_position.x)
if push == 0.0:
push = -direction
velocity = Vector2(push * knockback, -60.0)
if health <= 0:
_die()
else:
state = State.HURT
sprite.stop() # restart "hurt" even if it was playing
sprite.play("hurt")
func _flash() -> void:
if _flash_tween:
_flash_tween.kill()
sprite.modulate = Color(2.5, 2.5, 2.5) # values above 1 brighten the sprite
_flash_tween = create_tween()
_flash_tween.tween_property(sprite, "modulate", Color.WHITE, 0.15)
func _die() -> void:
state = State.DEAD
hitbox.set_deferred("monitoring", false) # no more contact damage
set_deferred("collision_layer", 0) # player and attacks pass through
sprite.stop()
sprite.play("death")
func _on_animation_finished() -> void:
if sprite.animation == &"death":
queue_free()
elif sprite.animation == &"hurt" and state == State.HURT:
_enter_idle()
func _on_hitbox_body_entered(body: Node2D) -> void:
if state != State.DEAD and body.has_method("take_damage"):
body.take_damage(contact_damage, global_position)
Drop a few slime.tscn instances on your level, make sure the floor is a TileMapLayer (Godot 4.3+) or TileMap / StaticBody2D on physics layer 1, and press F6. Without a player in the scene the slimes simply patrol and turn around at walls and ledges.
How the script works
Gravity and movement
CharacterBody2D in Godot 4 has a built-in velocity property, and move_and_slide() takes no arguments: it moves the body using velocity, slides along surfaces and updates is_on_floor(). Gravity is read once from the project setting physics/2d/default_gravity (980 px/s² by default), which works on every Godot 4 version. On 4.3 and later, get_gravity() returns the gravity vector at the body's position, including any Area2D gravity overrides, so velocity += get_gravity() * delta is a drop-in replacement.
The four states
- IDLE slows to a stop with friction and counts down
idle_time. When the timer runs out, the slime tries to hop. - HOP sets an upward and sideways velocity once and lets physics do the rest. The
_left_groundflag avoids a classic bug: right after take-off,is_on_floor()is still true until the nextmove_and_slide(), which would make the slime "land" instantly. - HURT plays the 2-frame hurt animation while knockback slides the slime back. When the animation finishes, it returns to IDLE.
- DEAD ignores further damage, disables the hitbox and the body's collision layer, plays the death animation and frees itself when it ends.
With the default numbers, a hop lasts about 0.37 s (2 × 180 / 980) and covers about 22 px. That is why FloorRay sits 20 px ahead: it checks the ground where the slime is about to land. If you change hop_speed or hop_force, move FloorRay accordingly.
Patrol vs. chase
Before each hop, the slime looks for the first node in the player group. If it is within detect_range, the slime faces it; otherwise it keeps its current direction, which gives you a free patrol. Then the rays are checked. A patrolling slime turns around at a wall or a ledge; a chasing slime just waits, so it will not throw itself off a platform to reach you. force_raycast_update() is called after flipping because rays normally update only once per physics frame.
Flipping
sprite.flip_h mirrors the image without touching the node's transform, so the collision shape and offset stay correct. The rays live under Facing, which is flipped with scale.x. (Avoid setting a negative scale.x on the CharacterBody2D itself: physics bodies do not support non-uniform or negative scale well.)
Hurt flash
Modulate multiplies the sprite's colours; values above 1 push every channel toward white, which gives a quick hit flash without a shader. The tween brings it back to Color.WHITE (no tint) in 0.15 s. If you want a perfectly white silhouette, use a small canvas_item shader with a flash uniform instead.
Death and animation_finished
AnimatedSprite2D emits animation_finished when a non-looping animation reaches its last frame. The handler compares sprite.animation (a StringName) with &"death" and calls queue_free(), which removes the slime safely at the end of the frame. Drop coins or play a sound in the same place.
Connecting it to your player
The slime only assumes three things about your player:
- The player node is in the
playergroup (Node dock > Groups, oradd_to_group("player")in its_ready()). - Its body is on physics layer 2, so the slime's Hitbox sees it.
- It has a
take_damage(amount, from_position)method.
To let the player hurt slimes, give the attack (sword swing, stomp, bullet) an Area2D with mask 3 enemies:
# On the player's attack Area2D (mask = layer 3 "enemies")
func _on_attack_area_body_entered(body: Node2D) -> void:
if body.is_in_group("enemies") and body.has_method("take_damage"):
body.take_damage(1, global_position)
If the player body's mask does not include layer 3, the player walks through slimes and only takes damage from the Hitbox, which is the usual feel for a platformer. Add layer 3 to the player's mask if you want slimes to block the player physically. Note that body_entered fires once per contact; for repeated damage while the player stays inside, give the player a short invincibility timer and check hitbox.get_overlapping_bodies() when it ends.
Alternative: Sprite2D with hframes, and the AnimationPlayer approach
Plain Sprite2D with hframes
A Sprite2D can also show one cell of a sheet. Set Texture to green_hop.png, Animation > Hframes to 6 and Vframes to 1, then change frame over time:
@onready var sprite: Sprite2D = $Sprite2D
var _time: float = 0.0
func _process(delta: float) -> void:
_time += delta
sprite.frame = int(_time * 10.0) % sprite.hframes # 10 FPS loop
This is fine for a single looping animation (a pickup, a torch). For several animations, use the combined sheet green_all.png with Hframes = 6 and Vframes = 4 and drive it with an AnimationPlayer, as below. The same rules apply: Offset (0, -8) for feet at the origin, and Flip H for direction.
AnimationPlayer
- Add an
AnimationPlayernext to theSprite2D. - Create an animation
hopwith length 0.6 s (6 frames at 10 FPS) and loop on. - Add a property track for
Sprite2D:frame_coordsand key(0, 1),(1, 1)…(5, 1)every 0.1 s (column, row). Set the track's update mode to Discrete. - Do the same for
idle(row 0, 4 keys every 1/6 s),hurt(row 2) anddeath(row 3, loop off). - In the script, replace
sprite.play(...)with$AnimationPlayer.play(...). AnimationPlayer'sanimation_finishedsignal passes the animation name:func _on_animation_finished(anim_name: StringName).
The advantage is that the same animation can key anything else at an exact time: enable the hitbox only on the frames where the slime is in the air, move the collision shape for the squash, or add a Call Method track that plays a sound on landing. For a simple slime, AnimatedSprite2D is less work; reach for AnimationPlayer when timing other properties matters.
Optional: attack and projectile animations
If your sprite set includes an attack and a projectile (Slime Forge DELUXE has attack 6 frames at 12 FPS, projectile 4 frames at 12 FPS looping, splash 3 frames at 12 FPS and spawn 5 frames at 10 FPS), you can turn the slime into a ranged enemy with a few additions. Import them exactly like the others, with loop on only for projectile.
enum State { IDLE, HOP, HURT, DEAD, ATTACK } # add ATTACK
@export var projectile_scene: PackedScene
@export var attack_range: float = 64.0
# In _ready():
sprite.frame_changed.connect(_on_frame_changed)
# In _physics_process(), handle ATTACK like HURT:
State.HURT, State.DEAD, State.ATTACK:
velocity.x = move_toward(velocity.x, 0.0, friction * delta)
# In _try_hop(), right after _set_facing(direction):
if chasing and projectile_scene and global_position.distance_to(player.global_position) <= attack_range:
state = State.ATTACK
sprite.play("attack")
return
func _on_frame_changed() -> void:
if state == State.ATTACK and sprite.animation == &"attack" and sprite.frame == 3:
var p := projectile_scene.instantiate()
p.direction = direction
p.global_position = global_position + Vector2(8.0 * direction, -6.0)
get_parent().add_child(p)
# In _on_animation_finished(), add:
elif sprite.animation == &"attack" and state == State.ATTACK:
_enter_idle()
The projectile is its own small scene: an Area2D (mask 1 world + 2 player) with an AnimatedSprite2D (Centered on, Offset (0, 0)) and a circle CollisionShape2D:
extends Area2D
@export var speed: float = 120.0
var direction: float = 1.0
var _done: bool = false
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
func _ready() -> void:
sprite.flip_h = direction < 0.0
sprite.play("projectile")
body_entered.connect(_on_body_entered)
sprite.animation_finished.connect(_on_animation_finished)
func _physics_process(delta: float) -> void:
if not _done:
position.x += speed * direction * delta
func _on_body_entered(body: Node2D) -> void:
if _done:
return
_done = true
if body.is_in_group("player") and body.has_method("take_damage"):
body.take_damage(1, global_position)
set_deferred("monitoring", false)
sprite.play("splash")
func _on_animation_finished() -> void:
if sprite.animation == &"splash":
queue_free()
Add a VisibleOnScreenNotifier2D to the projectile and connect its screen_exited signal to queue_free so missed shots do not live forever. For the spawn animation, set the state to a "busy" state in _ready(), play spawn, and call _enter_idle() when it finishes. A 32×32 boss such as the King Slime uses the same script with an Offset of (0, -16) and a larger collision shape; its slam animation slots in like attack.
Common pitfalls
- Blurry pixels. Default Texture Filter is still Linear, a parent node overrides Texture Filter, or the game is scaled by a fractional factor. Set Nearest and use integer scaling.
- The death animation loops forever and the slime never disappears. New SpriteFrames animations loop by default. Turn looping off for
deathandhurt; looping animations never emitanimation_finished(they emitanimation_looped). - Slime floats above or sinks into the floor. The sprite is centred on the node but the collision shape is not, or the other way round. Put the feet on the origin: sprite Offset (0, -8), collision shape bottom at y = 0.
- Hop ends immediately. Checking
is_on_floor()on the same frame you set the jump velocity. Wait until the body has left the floor once (the_left_groundflag). - Slime walks off ledges anyway. FloorRay is too close to the body for the hop distance, its mask does not include the world layer, or it was not flipped with the slime. Place it near the landing point and keep it under
Facing. - The slime damages itself or other slimes. The Hitbox mask includes the enemies layer. It should only include the player layer.
- "Can't change this state while flushing queries" errors. Changing collision properties inside a physics signal. Use
set_deferred(), as_die()does. - Extra blank frame in the animation. Empty cells of a combined sheet were added to SpriteFrames, or Horizontal does not match the real frame count.
- Godot 3 code from old tutorials.
KinematicBody2D,move_and_slide(velocity, Vector2.UP),export varandonready varare Godot 3. In Godot 4 they areCharacterBody2D,move_and_slide()with thevelocityproperty,@exportand@onready.
FAQ
Why are my pixel art sprites blurry in Godot 4?
Godot 4 filters canvas textures linearly by default. Set Project Settings > Rendering > Textures > Canvas Textures > Default Texture Filter to Nearest, or set Texture Filter to Nearest on the sprite node or a parent. Also check that the texture is imported without lossy compression and that the game is not scaled by a non-integer factor.
How do I add a sprite sheet to an AnimatedSprite2D in Godot 4?
Select the AnimatedSprite2D, create a New SpriteFrames in its Sprite Frames property and click it to open the SpriteFrames panel. Create or rename an animation, click Add frames from a Sprite Sheet, pick the PNG, set Horizontal to the number of frames and Vertical to the number of rows, select the frames and click Add Frames.
Why does animation_finished never fire on my AnimatedSprite2D?
animation_finished is only emitted by animations that do not loop. New animations in a SpriteFrames resource loop by default, so turn off the Animation Looping toggle for one-shot animations such as hurt and death. Looping animations emit animation_looped instead.
Should I use AnimatedSprite2D or AnimationPlayer for a 2D enemy?
AnimatedSprite2D is the quickest way to play frame-by-frame sprite animations and is enough for most small enemies. AnimationPlayer is better when an animation must also change other properties at precise times, such as enabling a hitbox, moving a collision shape or playing a sound on a specific frame.
How do I make an enemy turn around at ledges in Godot 4?
Put a RayCast2D slightly in front of the enemy pointing down and another at body height pointing forward. When the downward ray is not colliding there is a ledge, and when the forward ray is colliding there is a wall; in both cases reverse the direction. Flip the rays with the enemy, for example by setting the scale.x of their parent node to -1 or 1.
Why does my enemy float above or sink into the floor?
The sprite and the collision shape do not share the same bottom edge. A centred 16×16 sprite extends 8 pixels below its node, so if the artwork's feet are on the bottom row, set the sprite Offset to (0, -8) and place the collision shape so its bottom is at y = 0. Then the node position is the feet position.
Does this slime script work in Godot 4.0 and 4.1?
The script is written for Godot 4.2 and later but uses only APIs available since 4.0: CharacterBody2D.velocity, move_and_slide() without arguments, is_on_floor(), RayCast2D and AnimatedSprite2D.play(). It reads gravity from the project setting physics/2d/default_gravity; in Godot 4.3 and later you can use velocity += get_gravity() * delta instead.
Next steps
Once one slime works, make it a family: duplicate the SpriteFrames resource for each colour and give tougher colours more max_health or a shorter idle_time. The free slime pack already has 8 colours; for your own palettes, the Palette Swapper recolours whole sprite sheets in the browser, and the palette swap guide explains how to keep each variant readable.
Free: Animated Slime Enemies Pack
16×16 slimes in 8 colours with idle, hop, hurt and death animations, horizontal strips plus a combined sheet, frame data in JSON and Godot 4 import notes. Free for commercial games.
Download the free pack View on itch.io