Simple Spline-based Character Patrolling

From Epic Wiki
Spline00.jpg

Click for an animated example

Spline01.jpeg

This tutorial will show you how to create a character who will navigate along a path set by a spline.

First, add a Spline component to your character.

With your character selected in the world editor, you can edit a spline by clicking on and moving the points. Hold [ alt ] while moving a point to create a new one.

In your Construction Script , detach the Spline from your character with the DetachFromComponent node. This will keep the spline in place while your character moves around.

Select your Spline and from the Details tab, tick the Closed Loop option to join up the start and end points.

Variables
Name Type Description
Distance Float How far along the spline you are
Target Location Vector The next point that the character will try to reach
Patrol Speed Float How fast you want the target location to move along the spline (Default: 150)
Patrol Handle Timer Handle Used to control the timer responsible for triggering the movement.
Spline04.jpg

Simple Move to Location is the most basic way to drive your character.

Get the World location of the spline at the current Distance , this will be the point that your character tries to reach next.

Create a custom event to store this value in your Target Location variable, and to trigger the character to move.

Spline05.jpg

You will need to start a Looping Timer to repeatedly call your new event. This can be done with the BeginPlay event if you want the character to begin patrolling immediately, or selectively done only when/if you want the behaviour to start.

Storing the Handle as a variable allows us to easily pause/resume the timer when we want to toggle the patrolling (for example if they see the player and should chase them instead)

Spline06.jpg

When the Timer ticks, Patrol Speed is added to Distance to move it along the spline over time. If Distance becomes bigger than the length of the spline, they are subtracted from one another to bring Distance back into range.

And that should do it.

If your character doesn't move, make sure it and potential target points are within a Navmesh

If your character frequently stops, your Patrol Speed may be too low. Use a Draw Debug Line node to check where your Target Location is at each step. I use a value of ~150, but it will depend how fast your character moves.

If you find your spline remains attached to the character, recompile/save the blueprint.

Thanks for reading.

Original Author: