7. Moving actors
Prev | Chapter 5. Animations | Next

## 7. Moving actors

### 7.1. Problem

You want to animate the movement of one or more actors. For example:

- To move user interface elements in response to user input (e.g. keyboard control of a character in a game).

- To move a group of actors "off stage" to make way for another group of actors (e.g. paging through thumbnails in a photo viewer).

- To move an actor to a different position in the interface (e.g. moving an icon for a trashed file into a wastebin).

### 7.2. Solutions

Animate the actors movement on one or more axes (`x`, `y`, `z/depth`) using one or more of the approaches available in the Clutter API (implicit animations, ClutterState, ClutterAnimator).

#### 7.2.1. Solution 1: Implicit animations

This works well for simple movement of a single actor to a single set of coordinates. Here is an example of how to animate movement of a ClutterActor `actor` to position `100.0` on `x` axis:

    clutter_actor_animate (actor, CLUTTER_LINEAR, 500,
                           "x", 100.0,
                           NULL);

See this example which demonstrates movement in each axis, in response to (mouse) button presses.

#### 7.2.2. Solution 2: ClutterState

This suits simple, repeated movement of one or more actors between sets of coordinates. Here is an example of how to create two states for a ClutterState instance to move two actors, `actor1` and `actor2`:

    ClutterState *transitions = clutter_state_new ();

    /* all state transitions take 250ms */
    clutter_state_set_duration (transitions, NULL, NULL, 250);

    /* create a state called move-down which moves both actors to y = 200.0 */
    clutter_state_set (transitions, NULL, "move-down",
                       actor1, "y", CLUTTER_EASE_OUT_CUBIC, 200.0,
                       actor2, "y", CLUTTER_EASE_OUT_CUBIC, 200.0,
                       NULL);

    /* create a state called move-up which moves both actors to y = 0.0 */
    clutter_state_set (transitions, NULL, "move-up",
                       actor1, "y", CLUTTER_EASE_OUT_CUBIC, 0.0,
                       actor2, "y", CLUTTER_EASE_OUT_CUBIC, 0.0,
                       NULL);

    /* move the actors by setting the state */
    clutter_state_set (transitions, "move-down");

This full example shows how to move and simultaneously scale two actors. When a button is pressed on one actor, it is moved and scaled to occupy the right-hand side of the stage; the other actor is simultaneously moved back to the left-hand side of the stage and scaled down.

#### 7.2.3. Solution 3: ClutterAnimator

This is a good way to implement complex movement of one or more actors between sets of coordinates.

    ClutterAnimator *animator = clutter_animator_new ();

    /* the animation takes 500ms */
    clutter_animator_set_duration (animator, 500);

    /* at the start of the animation, actor should be at 0.0,0.0;
     * half-way through, at 100.0,100.0;
     * by the end, actor should be at 150.0,200.0;
     * note that you can set different easing modes for each
     * part of the animation and for each property at each key
     */
    clutter_animator_set (animator,

                          /* keys for the start of the animation */
                          actor, "x", CLUTTER_LINEAR, 0.0, 0.0,
                          actor, "y", CLUTTER_LINEAR, 0.0, 0.0,

                          /* keys for half-way through the animation */
                          actor, "x", CLUTTER_EASE_OUT_CUBIC, 0.5, 100.0,
                          actor, "y", CLUTTER_EASE_IN_CUBIC, 0.5, 100.0,

                          /* keys for the end of the animation */
                          actor, "x", CLUTTER_EASE_OUT_EXPO, 1.0, 150.0,
                          actor, "y", CLUTTER_EASE_OUT_CUBIC, 1.0, 200.0,

                          NULL);

    /* run the animation */
    clutter_animator_start (animator);

The full example demonstrates how ClutterAnimator can be used to programmatically animate multiple actors: in this case, to simultaneously move three actors to random positions along the `x` axis. Synchronising the movement of three actors simultaneously using implicit animations would be possible but awkward; ClutterState might be another option, but it wasn't really designed for this case: there are no persistent states to transition between, as the actor positions are generated on each key press.

### Note

If you want to apply the same movement to a group of actors, rather than different movements for each actor, it's often better to put the actors into a container of some kind and move that instead of moving the actors individually.

### 7.3. Discussion

#### 7.3.1. Movement can take an actor "outside" its container

Actor movement in the `x` and `y` axes is relative to the actor's parent container. There is nothing to stop you animating an actor until it falls outside the bounds of its container. This could result in the actor moving "off" the interface; though it's worth remembering that the actor is not unparented or destroyed if this happens.

To ensure that an actor remains visible, its position should remain within the visible area of the container. In practice, this means either anywhere in the container, if no clip area has been set; or within the container's clip area, if set.

#### 7.3.2. Anchor points can affect movement

An actor's anchor point is defined as an `x,y` coordinate relative to the top-left of the actor. The default anchor point for an actor is in its top-left corner. However, it is possible to set this to some other coordinate, relative to the actor's top-left corner, using the `clutter_anchor_set_anchor_point()` function.

For example:

    /* set the actor's size to 100px x 100px */
    clutter_actor_set_size (actor, 100, 100);

    /* set an anchor point half-way along the top of the actor */
    clutter_actor_set_anchor_point (actor, 50.0, 0.0);

### Note

In GL terms, the anchor point of an actor is the equivalent of applying an additional transformation of `-x, -y` to the actor's modelview. If the anchor point is `0, 0`, i.e. the top-left corner, then the transformation will leave the actor in the same place.

It is important to note that the anchor point will affect the position in which an actor is painted, but will not change the position or size that its parent allocated for it.

Finally, the anchor point will affect the other transformations that can be applied to an actor: scaling and rotating.

A positive anchor point within the width/height bounds of the actor is inside the actor. An anchor point outside these bounds is outside the actor. You can also set a negative `x` or `y` value for the anchor point, which will again place the point outside the actor's bounds.

This is important with respect to moving an actor, because you are actually moving the anchor point and "dragging" the actor along with it.

For example: you have an actor with width 50px, and you set its `anchor-x` property to `25.0`. If you move that actor on the `x` axis, you are effectively moving a point half-way across the top of the actor along the `x` axis (which in turn moves the actor).

Similarly, you could set the same actor's `anchor-x` to `-25.0`. If you then moved the actor along the `x` axis, you would effectively be moving the point 25px left of the top of the actor along that axis.

The video below demonstrates the effect on movement of shifting the anchor point on the `x` axis. The red rectangle has `anchor-x` set to `25.0`; the green rectangle has `anchor-x` set to `0.0` (the default); the blue rectangle has `anchor-x` set to `-25.0`.

A ClutterAnimator is used to move each of the rectangles to `x = 225.0`. Although the three rectangles move to the same position on the `x` axis, it's actually the anchor points which are at the same position. These all align on the `x` axis with the left-hand edge of the green rectangle.

#### 7.3.3. Actors can move in the `z` axis

The examples so far have shown how to move actors in the `x` and `y` axes; but it is also possible to move actors in the `z` axis (i.e. move them closer or further away from the view point). This lets you move actors under/over each other.

To move an actor in the `z` axis, animate its `depth` property. Animating to a negative depth moves the actor away from the view point; animating to a positive depth moves the actor towards the view point.

Changing the depth of an actor also causes perspective effects: the actor gets smaller and converges on the center of the stage as it gets further from the view point, and gets larger and diverges from the center of the stage as it gets closer. This results in an apparent (but not actual) change in the `x,y` position and scale of the actor.

### Note

Animating the depth of an actor is slightly different from animating its x and y coordinates, as depth is relative to the whole stage, not just the parent container of the actor. This means that perspective effects are with respect to the whole stage: so as an actor's depth moves below `0.0`, it converges on the center of the stage, and may even apparently move outside its container (if the container stays at the same depth).

The video below demonstrates the effect of animating the depth of four actors to a value of `-15000.0`. Note how the actors converge on the center of the stage, as well as appearing to change position and scale; also note that they appear to move outside the bounds of their parent containers (the four yellow ClutterBoxes).

#### 7.3.4. Movement is affected by constraints

An actor can have its x,y position constrained by the position of other actors through ClutterBindConstraints. This can affect movement in two ways:

1. If an actor has its `x` and/or `y` properties bound or aligned to another actor's, you can't animate those properties.

   In effect this means that the bound actor can't be moved on a bound axis directly, but can only be moved by animating the constraint's properties.

2. If you move an actor which has other actors bound to it, the bound actors will also move. For example, if the actor has several other actors whose `x` properties are bound to its `x` property, moving the actor on the `x` axis will also move the bound actors on that axis.

   Similarly, if some actor is the source for alignment constraints on other actors, moving the source will cause those other actors to move, so that they remain in alignment with it.

For example, consider two actors bound by constraints as follows:

    /* the source actor for the constraint */
    ClutterActor *source;

    /* the actor bound by the constraint */
    ClutterActor *target;

    /* a constraint to be added to target */
    ClutterConstraint *constraint;

    /* ...initialize actors etc... */

    /* create a constraint for binding the x position of some actor to the
     * x position of source
     */
    constraint = clutter_bind_constraint_new (source, CLUTTER_BIND_X, 0.0);

    /* add the constraint to target with a name */
    clutter_actor_add_constraint_with_name (target, "bind-x", constraint);

Animating `source` on the `x` axis also animates `target` on the same axis:

    clutter_actor_animate (source, CLUTTER_LINEAR, 500,
                           "x", 250.0,
                           NULL);

...while this has no effect, as it would violate `constraint` (it's best not to animate `target's` `x` property directly):

    clutter_actor_animate (target, CLUTTER_LINEAR, 500,
                           "x", 250.0,
                           NULL);

But the constraint's properties can be animated, to change how `source` and `target` are bound; which in turn moves `target`:

    clutter_actor_animate (target, CLUTTER_LINEAR, 500,
                           "@constraints.bind-x.offset", 250.0,
                           NULL);

Note the `@constraints.<constraint name>.<constraint property>` syntax (which is why we needed to use `clutter_actor_add_constraint_with_name()`, so that the constraint can be accessed through the actor). We are still animating `target`, but really we're indirectly animating a property of one of its constraints.

Another alternative would be to directly animate the constraint's properties through ClutterState or ClutterAnimator, rather than using pseudo-properties on the actor animation:

    ClutterAnimator *animator = clutter_animator_new ();
    clutter_animator_set_duration (animator, 500);

    clutter_animator_set (animator,
                          constraint, "offset", CLUTTER_LINEAR, 0.0, 0.0,
                          constraint, "offset", CLUTTER_LINEAR, 1.0, 250.0,
                          NULL);

    clutter_animator_start (animator);

This could be useful if you need to animate multiple constraints between multiple values simultaneously.

### 7.4. Full examples

Example 5.8. Simple movement using implicit animations

    #include <stdlib.h>
    #include <clutter/clutter.h>

    typedef struct
    {
      gchar *axis;
      gfloat target;
    } AnimationSpec;

    static gboolean
    button_pressed_cb (ClutterActor *actor,
                       ClutterEvent *event,
                       gpointer      user_data)
    {
      AnimationSpec *animation_spec = user_data;
      ClutterTransition *transition;

      if (clutter_actor_get_transition (actor, animation_spec->axis) != NULL)
        return TRUE;

      clutter_actor_save_easing_state (actor);
      clutter_actor_set_easing_duration (actor, 500);

      g_object_set (actor, animation_spec->axis, animation_spec->target, NULL);
      transition = clutter_actor_get_transition (actor, animation_spec->axis);
      clutter_timeline_set_auto_reverse (CLUTTER_TIMELINE (transition), TRUE);
      clutter_timeline_set_repeat_count (CLUTTER_TIMELINE (transition), 1);

      clutter_actor_restore_easing_state (actor);

      return TRUE;
    }

    int
    main (int   argc,
          char *argv[])
    {
      ClutterActor *stage;
      ClutterActor *rectangle1;
      ClutterActor *rectangle2;
      ClutterActor *rectangle3;

      AnimationSpec x_move = { "x", 50.0 };
      AnimationSpec y_move = { "y", 400.0 };
      AnimationSpec z_move = { "depth", -1000.0 };

      if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS)
        return 1;

      stage = clutter_stage_new ();
      clutter_actor_set_size (stage, 500, 500);
      clutter_stage_set_color (CLUTTER_STAGE (stage), CLUTTER_COLOR_Aluminium2);
      g_signal_connect (stage, "destroy", G_CALLBACK (clutter_main_quit), NULL);

      rectangle1 = clutter_actor_new ();
      clutter_actor_set_background_color (rectangle1, CLUTTER_COLOR_ScarletRed);
      clutter_actor_set_reactive (rectangle1, TRUE);
      clutter_actor_set_size (rectangle1, 50, 50);
      clutter_actor_set_position (rectangle1, 400, 400);
      clutter_actor_add_child (stage, rectangle1);

      rectangle2 = clutter_actor_new ();
      clutter_actor_set_background_color (rectangle2, CLUTTER_COLOR_Chameleon);
      clutter_actor_set_reactive (rectangle2, TRUE);
      clutter_actor_set_size (rectangle2, 50, 50);
      clutter_actor_set_position (rectangle2, 50, 50);
      clutter_actor_add_child (stage, rectangle2);

      rectangle3 = clutter_actor_new ();
      clutter_actor_set_background_color (rectangle3, CLUTTER_COLOR_SkyBlue);
      clutter_actor_set_reactive (rectangle3, TRUE);
      clutter_actor_set_size (rectangle3, 50, 50);
      clutter_actor_set_position (rectangle3, 225, 225);
      clutter_actor_add_child (stage, rectangle3);

      g_signal_connect (rectangle1,
                        "button-press-event",
                        G_CALLBACK (button_pressed_cb),
                        &x_move);

      g_signal_connect (rectangle2,
                        "button-press-event",
                        G_CALLBACK (button_pressed_cb),
                        &y_move);

      g_signal_connect (rectangle3,
                        "button-press-event",
                        G_CALLBACK (button_pressed_cb),
                        &z_move);

      clutter_actor_show (stage);

      clutter_main ();

      return EXIT_SUCCESS;
    }

Example 5.9. Using ClutterState to repeatedly move (and scale) two actors

    #include <stdlib.h>
    #include <clutter/clutter.h>

    static const ClutterColor stage_color = { 0x33, 0x33, 0x55, 0xff };
    static const ClutterColor red_color = { 0xff, 0x00, 0x00, 0xff };
    static const ClutterColor green_color = { 0x00, 0xff, 0x00, 0xff };

    static gboolean
    button_pressed_cb (ClutterActor *actor,
                       ClutterEvent *event,
                       gpointer      user_data)
    {
      ClutterState *transitions = CLUTTER_STATE (user_data);

      /* set the state to the one with a name matching the actor's name */
      clutter_state_set_state (transitions, clutter_actor_get_name (actor));

      return TRUE;
    }

    int
    main (int   argc,
          char *argv[])
    {
      ClutterActor *stage;
      ClutterActor *red;
      ClutterActor *green;
      ClutterState *transitions;

      if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS)
        return 1;

      stage = clutter_stage_new ();
      clutter_actor_set_size (stage, 650, 500);
      clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);
      g_signal_connect (stage, "destroy", G_CALLBACK (clutter_main_quit), NULL);

      /* actor names choose the next ClutterState to transition to */
      red = clutter_rectangle_new_with_color (&red_color);
      clutter_actor_set_reactive (red, TRUE);
      clutter_actor_set_name (red, "red");
      clutter_actor_set_size (red, 100, 100);
      clutter_actor_set_position (red, 50, 50);

      green = clutter_rectangle_new_with_color (&green_color);
      clutter_actor_set_reactive (green, TRUE);
      clutter_actor_set_name (green, "green");
      clutter_actor_set_size (green, 100, 100);
      clutter_actor_set_position (green, 50, 350);

      transitions = clutter_state_new ();
      clutter_state_set_duration (transitions, NULL, NULL, 250);

      /* state names match actor names */
      clutter_state_set (transitions, NULL, "red",
                         red, "x", CLUTTER_EASE_OUT_CUBIC, 200.0,
                         red, "y", CLUTTER_EASE_OUT_CUBIC, 50.0,
                         red, "scale-x", CLUTTER_EASE_OUT_CUBIC, 4.0,
                         red, "scale-y", CLUTTER_EASE_OUT_CUBIC, 4.0,
                         green, "x", CLUTTER_EASE_OUT_CUBIC, 50.0,
                         green, "y", CLUTTER_EASE_OUT_CUBIC, 350.0,
                         green, "scale-x", CLUTTER_EASE_OUT_CUBIC, 1.0,
                         green, "scale-y", CLUTTER_EASE_OUT_CUBIC, 1.0,
                         NULL);

      clutter_state_set (transitions, NULL, "green",
                         green, "x", CLUTTER_EASE_OUT_CUBIC, 200.0,
                         green, "y", CLUTTER_EASE_OUT_CUBIC, 50.0,
                         green, "scale-x", CLUTTER_EASE_OUT_CUBIC, 4.0,
                         green, "scale-y", CLUTTER_EASE_OUT_CUBIC, 4.0,
                         red, "x", CLUTTER_EASE_OUT_CUBIC, 50.0,
                         red, "y", CLUTTER_EASE_OUT_CUBIC, 50.0,
                         red, "scale-x", CLUTTER_EASE_OUT_CUBIC, 1.0,
                         red, "scale-y", CLUTTER_EASE_OUT_CUBIC, 1.0,
                         NULL);

      g_signal_connect (red,
                        "button-press-event",
                        G_CALLBACK (button_pressed_cb),
                        transitions);

      g_signal_connect (green,
                        "button-press-event",
                        G_CALLBACK (button_pressed_cb),
                        transitions);

      clutter_container_add (CLUTTER_CONTAINER (stage),
                             red,
                             green,
                             NULL);

      clutter_actor_show (stage);

      clutter_main ();

      g_object_unref (transitions);

      return EXIT_SUCCESS;
    }

Example 5.10. Using ClutterAnimator to randomly move three actors along the `x` axis

    #include <stdlib.h>
    #include <clutter/clutter.h>

    typedef struct
    {
      ClutterActor    *stage;
      ClutterActor    *group;
      ClutterAnimator *animator;
    } State;

    static const ClutterColor stage_color = { 0x33, 0x33, 0x55, 0xff };
    static const ClutterColor red_color = { 0xff, 0x00, 0x00, 0xff };
    static const ClutterColor green_color = { 0x00, 0xff, 0x00, 0xff };
    static const ClutterColor blue_color = { 0x00, 0x00, 0xff, 0xff };

    /* add keys to the animator such that the actor is moved
     * to a random x position
     */
    static void
    add_keys_for_actor (ClutterActor    *actor,
                        ClutterAnimator *animator)
    {
      gfloat x, end_x;

      x = clutter_actor_get_x (actor);

      end_x = 50.0;
      if (x == 50.0)
        end_x = 225.0 + (100.0 * rand () / (RAND_MAX + 1.0));

      clutter_animator_set (animator,
                            actor, "x", CLUTTER_LINEAR, 0.0, x,
                            actor, "x", CLUTTER_EASE_OUT_CUBIC, 1.0, end_x,
                            NULL);
    }

    static gboolean
    move_actors (ClutterActor *actor,
                 ClutterEvent *event,
                 gpointer      user_data)
    {
      State *state = user_data;
      ClutterActor *child;

      /* do nothing if the animator is already running */
      if (clutter_timeline_is_playing (clutter_animator_get_timeline (state->animator)))
        return TRUE;

      /* remove all keys from the animator */
      clutter_animator_remove_key (state->animator, NULL, NULL, -1);

      /* add keys for all actors in the group */
      for (child = clutter_actor_get_first_child (state->group);
           child != NULL;
           child = clutter_actor_get_next_sibling (child))
        {
          add_keys_for_actor (child, state->animator);
        }

      /* start the animation */
      clutter_animator_start (state->animator);

      return TRUE;
    }

    int
    main (int   argc,
          char *argv[])
    {
      ClutterActor *red;
      ClutterActor *green;
      ClutterActor *blue;

      State *state = g_new0 (State, 1);

      /* seed random number generator */
      srand ((unsigned int) time (NULL));

      if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS)
        return 1;

      state->animator = clutter_animator_new ();
      clutter_animator_set_duration (state->animator, 500);

      state->stage = clutter_stage_new ();
      clutter_actor_set_size (state->stage, 400, 350);
      clutter_stage_set_color (CLUTTER_STAGE (state->stage), &stage_color);
      g_signal_connect (state->stage,
                        "destroy",
                        G_CALLBACK (clutter_main_quit),
                        NULL);

      state->group = clutter_actor_new ();
      clutter_actor_add_child (state->stage, state->group);

      red = clutter_actor_new ();
      clutter_actor_set_background_color (red, &red_color);
      clutter_actor_set_size (red, 50, 50);
      clutter_actor_set_position (red, 50, 50);
      clutter_actor_add_child (state->group, red);

      green = clutter_actor_new ();
      clutter_actor_set_background_color (green, &green_color);
      clutter_actor_set_size (green, 50, 50);
      clutter_actor_set_position (green, 50, 150);
      clutter_actor_add_child (state->group, green);

      blue = clutter_actor_new ();
      clutter_actor_set_background_color (blue, &blue_color);
      clutter_actor_set_size (blue, 50, 50);
      clutter_actor_set_position (blue, 50, 250);
      clutter_actor_add_child (state->group, blue);

      g_signal_connect (state->stage,
                        "key-press-event",
                        G_CALLBACK (move_actors),
                        state);

      clutter_actor_show (state->stage);

      clutter_main ();

      g_object_unref (state->animator);
      g_free (state);

      return EXIT_SUCCESS;
    }

Prev | Up | Next
6. Reusing a complex animation on different actors | Home | 8. Looping an animation