Control player along a path.

Wanted to control an object along a path? Here's a brief run-down on how I achieved path control in Fluffy Gunners

Posted by on - Intermediate Animation

During the development of Fluffy Gunners in Unity I used paths to control movement of the players and enemies. I thought I’d briefly go over how to control movement along a path.

I used iTweens which is free on the Asset store to control the paths. With iTweens you can draw a path by adding and moving control points and assign it a string identifier path name, paths can either be looping or open.

I found that built in path tweening functions generally only work when tween from one point to another, and start over from the beginning when ended. This did not suit my needs for Fluffy Gunners, where I wanted to control the player and enemies continuously along a path.

Instead I controlled the position along the length of the path and updated the object position each update.

From the path you can determine the world co-ordinates from any percentage of the path length (from 0 – 1), and can place an object on any point of the path.

To put an object on any position along the path you just need a reference to the path and the path percent.

iTween.PutOnPath(gameObject.transform, iTweenPath.GetPath(“pathname”), pathPercent);

To then move along the path, increase or decrease the pathPercent variable, keeping it within the 0-1 range to stay in the path bounds. You can update the path percent by adding or subtracting to the pathPercent variable. (I’ve also included another variable shipSpeedVariable to control the object speed along the path.)

pathPercent += Time.deltaTime * shipSpeedVariable; // call when moving left

pathPercent -= Time.deltaTime * shipSpeedVariable; // call when moving left

To keep the pathPercent variable within the 0-1 range, there is a handy Mathf function to do just that!

Mathf.Repeat(pathPercent, 1f);

With these functions you can control a character along a looped path, or loop around an open path. If you want to limit movement to the edges of the path remove the Mathf.Repeat function and clamp the values between 0 and 1 instead.

Mathf.Clamp(pathpercent, 0f, 1f);

It is not much of a stretch to then tween the path percent value to create smooth tweened enemy movement patterns, and to even seek other objects on the path.

I hope you found the article interesting, next time I'll talk about updating the path for 3d dimensional movement along an extruded path which I used for enemy movements in Fluffy Gunners.