Skip to content

4. Tweening Along a Path or Spline

MartinSchultz edited this page Oct 9, 2013 · 3 revisions

With GoKit you can tween an object along a path. There are a built-in tween properties for tweening position and scale using a Vector3 path and there is a generic Vector3 path tween property that can be used with any object. You can create your paths either using the GoKit visual path editor or in code by providing a list or array of Vector3s. The GoVector3Path class also provides some convenience methods allowing you to close a path (make it end and start at the same location for smooth movement) or reverse it.

Here is an example of moving an object along a closed path for 2 iterations:

var points = new Vector3[] { new Vector3( 0, 0, 0 ), new Vector3( 5, 5, 0 ), new Vector3( 0, 0, 0 ), new Vector3( -10, 0, 0 ) };
var path = new GoSpline( points );
path.closePath();

Go.to( someTransform, 3f, new GoTweenConfig().positionPath( path, true ) );

In the example you will notice that when creating the actual TweenProperty (the positionPath method) the second parameter was passed in as true. That parameter controls whether the tween is relative or not. Relative tweens treat the passed in endValue as relative instead of absolute. This means that the object will move by the value instead of to it. Using paths with isRelative set to true is a powerful way to animate objects. If your path starts at 0, 0, 0 then you can animate any object anywhere in world space using the path and it will follow along as if it was positioned right at the path's root node. The visual path editor has a handy button that allows you to shift a path so that it starts at the origin.

Visual Path Editor

Speaking of the visual path editor, you can access it by creating an empty GameObject and adding the GoDummyPath script to it. The script is named in such a way that it will remind you do delete it when done editing your paths (hopefully). It is not required at runtime at all. The script is only needed when editing paths in the editor. The visual path editor lets you create, load and save paths right in the Unity editor.

GoKit has a few different types of splines available that are automatically selected for you. If you have 2 points in your path obviously only a straight line is possible. If you have 3 points a quadratic bezier is used. If you have 4 points a cubic bezier is used and if you have more than 4 points a Catmull-Rom spline is used. The visual editor will automatically adjust itself depending on which spline type is used. If you want to use a straight line path even though you have more than 4 nodes you can do so by using the alternate constructor for the GoSpline class passing true as the second parameter.