All lessons
Lesson 06

Enemy Follows Player

Subtract two positions to get an arrow pointing at the player, then walk along it. That is the whole trick.

Loading the game engine. This takes a moment the first time.

The enemy has no code in this file. Everything it does lives in chaser_enemy.gd. This file just holds the scene together.

HOW CHASING WORKS

Take the target's position and subtract your own. That gives you an arrow pointing at them. Shrink the arrow to length 1, multiply it by your speed, and you have a velocity. It is the same math for anything that homes in: a chasing enemy, a guided missile, a pet that follows.

The scenes

UI node · 2D node · % unique name · .tscn instanced scene

enemy_follows_player.tscn
  • EnemyFollowsPlayer Node2D enemy_follows_player.gd
  • ChasePlayer CharacterBody2D player.tscn
  • ChaserEnemy1 CharacterBody2D chaser_enemy.tscn
  • ChaserEnemy2 CharacterBody2D chaser_enemy.tscn
chaser_enemy.tscn
  • ChaserEnemy CharacterBody2D chaser_enemy.gd
  • ColorRect
  • CollisionShape2D
player.tscn
  • ChasePlayer CharacterBody2D player.gd
  • Sprite2D
  • CollisionShape2D
extends Node2D