Paul
Paul

Reputation: 21975

Sequence of animations in WPF with BeginAnimation

I'm trying to animate some rotations in 3D with WPF and if I trigger them manually (on click) everything is fine, but if I compute the movements that should be made on the Viewport3D all animations seem to go off at the same time.

The code that computes the movements is as follows:

for(int i=0; i<40; i++){
    foo(i);
}

Where the foo(int i) looks like:

//compute axis, angle
AxisAngleRotation3D rotation = new AxisAngleRotation3D(axis, angle);
RotateTransform3D transform = new RotateTransform3D(rotation, new Point3D(0, 0, 0));
DoubleAnimation animation = new DoubleAnimation(0, angle, TimeSpan.FromMilliseconds(370)); 

rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, animation);

The computation of axis and angle is not something time consuming, simple attributions, so I guess the problem is that all animations trigger the next frame since the computations are already done when the current frame is "over".

How can I display those animations sequentially, rather than all at once, in code (not XAML)?

PS: everything is in C#, no XAML.

Upvotes: 1

Views: 2990

Answers (1)

Clemens
Clemens

Reputation: 128061

You may add multiple animations to a Storyboard and set each animation's BeginTime to the sum of the durations of the previous animations:

var storyboard = new Storyboard();
var totalDuration = TimeSpan.Zero;

for (...)
{
    var rotation = new AxisAngleRotation3D(axis, angle);
    var transform = new RotateTransform3D(rotation, new Point3D(0, 0, 0));
    var duration = TimeSpan.FromMilliseconds(370);
    var animation = new DoubleAnimation(0, angle, duration);

    animation.BeginTime = totalDuration;
    totalDuration += duration;

    Storyboard.SetTarget(animation, rotation);
    Storyboard.SetTargetProperty(animation, new PropertyPath(AxisAngleRotation3D.AngleProperty));

    storyboard.Children.Add(animation);
}

storyboard.Begin();

Note that i haven't tested the code above, so sorry for any faults.


Or you create your animations in a way that each animation (starting from the second one) is started in a Completed handler of the previous one.

Upvotes: 1

Related Questions