move shape

In this tutorial, we will move a shape.
We use a timer to animate the shape.

TimeSensor node generate periodic values.
We use it to animate the node.

Note:
See TimeSensor node documentation to more information.

We define a "ANIM_TIMER" timer (a TimeSensor node).
When widget is launch, timer is activated ("isActive TRUE") and timer cycle interval is 4 seconds.
At end of time interval (after 4 seconds), timer is relaunched ("loop TRUE").
Time sensor declaration:


We catch timer pulse with fraction_changed (SFFloat - value between 0.0 (animation start) and 1.0 (end of animation)).
We catch end of loop with cycleTime (SFTime - current time).


We have the timer.
We define a shape (a simple rectangle):


To move rectangle, we use a Transform2D node:


We have the timer, the shape... We will now animate the shape.


To create animation, we can use Interpolators nodes (CoordinateInterpolator, ColorInterpolator, ...).
To move a shape, we use PositionInterpolator2D node.
See other Interpolators documentation to rotate, change color, ...

We define 4 positions for animations: (-10, -10), (-10, 10), (10, 10) and (10, -10).
Shape move between this points.
When timer faction is 0.00, shape is at (-10,-10) position.
When timer faction is 0.25, shape is at (-10,10) position.
When timer faction is 0.50, shape is at (10,10) position.
When timer faction is 0.75, shape is at (10,-10) position.
And when timer faction is 1.00, shape is return at (-10,-10) position.


Link the Interpolator with the timer:


Link the Interpolator with the shape:


Final code for the first example:


Interpolators node are easy to used. But for complex animation, we can use a JavaScript function.
Example, if the shape moves on a circle.

Create a script node to the animation.


This script receive timer event fraction_changed (SFFloat type) and return the shape position (SFVec2f type).
Event in/out declaration:


Animation function transform a data between 0.0 and 1.0 in shape position (position on a circle).
We convert timer data in angle between 0 and 2PI. And we convert angle in position with cosine and sinus.


And we link script with the timer and the shape.


Final code for the second example: