How could I make an NPC circle a target like a shark?

Title says it all. I want to make an NPC circle it’s target. I’ve already taken care of how the NPC can distance itself from a target, but I don’t know where i’d start with making it circle an enemy like a shark.

Visual examples


if an object’s velocity is always adjusted to be perpendicular to a point, it will follow a circular path about a point.

  1. Get the vector of TargetPos-attackerPos
  2. turn the vector into vector2 because it is a 2d problem
  3. rotate the vector 90 degrees (-y,x)
  4. Move forward in the direction the vector is pointing (convert it to 3d if necessary)

You may wish to tighten the circle if the length of the vector found in step 1 is too long. In this case you can use a lerp changing the forward velocity to point more toward the center point by adjusting the alpha parameter.

What pathfinding are you using for the distancing? You could do something like:

count = 0

repeat
count += 1 -- change this to how many degrees apart the waypoints will be around the circle

local direction  = target.Position - attacker.Position
local distance = direction.Magnitude
	
pos = Vector3.new(math.sin(math.rad(count)) * distance, 0, math.cos(math.rad(count)) * distance) + target.Position
	
-- in here make the attacker walk to pos and a wait until they get there to continue the loop

until false