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.
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.
Related
I have a mini-game as part of a larger game I'm writing for Windows phone which uses a storyboard animation to move an arrow back and forth along a bar, which the user trying to stop it in the center.
The issue I'm having is when I stop the animation, you can visibily see the arrow being animated move back a frame.
I've tried many things:
animating with keyframes and without
animating by canvas.left or translate.X
after pausing/stopping the animation, manually setting the canvas.left to the getcanvas of the arrow
With the final option not working, I wonder if the animation is actually drawing a frame ahead before it actually sets the X/Canvas.Left, and the bounce back position is the true one
Here is my animation code:
double speed = .75;
miniGameStoryboard.Stop();
miniGameStoryboard.Children.Clear();
// setup
var _Translate = new TranslateTransform();
this.MiniGame1Arrow.RenderTransform = _Translate;
// translate (location X)
DoubleAnimationUsingKeyFrames _TranslateAnimateX = new DoubleAnimationUsingKeyFrames();
System.Windows.Media.Animation.Storyboard.SetTarget(_TranslateAnimateX, _Translate);
System.Windows.Media.Animation.Storyboard.SetTargetProperty(_TranslateAnimateX, new PropertyPath(TranslateTransform.XProperty));
_TranslateAnimateX.KeyFrames.Add(new LinearDoubleKeyFrame
{
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)),
Value = 0
});
_TranslateAnimateX.KeyFrames.Add(new LinearDoubleKeyFrame
{
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(speed)),
Value = 660
});
_TranslateAnimateX.AutoReverse = true;
_TranslateAnimateX.RepeatBehavior = RepeatBehavior.Forever;
_TranslateAnimateX.FillBehavior = FillBehavior.HoldEnd;
miniGameStoryboard.Children.Add(_TranslateAnimateX);
miniGameStoryboard.Begin();
The purpose of the code below is that a thumb follows a horizontal mouse movement. The code is called upon a mouse event, so the target value of the animation gets updated continuously.
In the code, offset is the current mouse horizontal position. The problem is, that the animation of the thumb doesn't fully animate to the specified offset, but always seems to be stopping at a value smaller or higher (depending if the mouse is dragged left or right).
The SeekAlignedToLastTick() influences the behavior of the animation, although I couldn't figure out what this function does by reading the documentation.
How can I animate the thumb, so that it follows smoothly the drag event?
private Storyboard _thumbStoryboard;
private DoubleAnimation _thumbAnimation = new DoubleAnimation();;
private CompositeTransform _thumbTransform = new CompositeTransform();
private void UpdateUserInterface(double offset)
{
var thumbItem = Thumb as FrameworkElement;
if (_thumbStoryboard == null)
{
Storyboard.SetTarget(_thumbAnimation, _thumbTransform);
_thumbStoryboard = new Storyboard();
_thumbStoryboard.Children.Add(_thumbAnimation);
thumbItem.RenderTransform = _thumbTransform;
_thumbStoryboard.Duration = new Duration(TimeSpan.FromMilliseconds(100));
_thumbAnimation.EasingFunction = new ExponentialEase();
}
double from = _thumbTransform.TranslateX;
_thumbStoryboard.Stop();
Storyboard.SetTargetProperty(_thumbAnimation, new PropertyPath("TranslateX"));
_thumbAnimation.From = from;
_thumbAnimation.To = offset;
_thumbStoryboard.Begin();
_thumbStoryboard.SeekAlignedToLastTick(TimeSpan.Zero);
}
I've tried to solve your issue, So I've created a Silverlight application and added a Border element for testing.
<Border x:Name="Thumb" VerticalAlignment="Top" HorizontalAlignment="Left" Width="50" height="25" Background="#ff0000" />
There was no need to set the "From" Property, since the DoubleAnimation object could automatically continue from the current Value to the "To" Property.
And you were setting the Duration to the Storyboard, which causes the DoubleAnimation to Cutoff its animation without reaching the "To" Value, You need to set the Duration Property to the DoubleAnimation itself instead.
Also there was no need to call _thumbStoryboard.Stop(), because it will reset the current animation to the first TranslateX Value.
Here is the updated "UpdateUserInterface" function code with comments:
private void UpdateUserInterface(double offset) {
var thumbItem = Thumb as FrameworkElement;
if ( _thumbStoryboard == null ) {
// UpdateLayout Method is update the ActualWidth Properity of the UI Elements
this.UpdateLayout();
// Applying the CompositeTransform on "thumbItem" UI Element
thumbItem.RenderTransform = _thumbTransform;
// Setting the Render Transform Origin to be the Center of X and Y
thumbItem.RenderTransformOrigin = new Point(0.5d, 0.5d);
// Setting the target of the DoubleAnimation to be the Thumb CompositeTransform
Storyboard.SetTarget(_thumbAnimation, _thumbTransform);
// Setting the Targeted Properity of the DoubleAnimation to be The "TranslateX" Properity
Storyboard.SetTargetProperty(_thumbAnimation, new PropertyPath("TranslateX"));
// Used QuinticEase instead of ExponentialEase
// and Added EaseOut to make the animation be more smoother.
_thumbAnimation.EasingFunction = new QuinticEase(){ EasingMode = EasingMode.EaseOut };
// Initializing the Storyboard
_thumbStoryboard = new Storyboard();
// Specifing the Duration of the DoubleAnimation not the StoryBoard
_thumbAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
// Adding the DoubleAnimation to the Children of the Storyboard
_thumbStoryboard.Children.Add(_thumbAnimation);
}
// Calculate the New Centered Position
double newPos = offset - (thumbItem.ActualWidth / 2);
// Set the New DoubleAnimation "To" Value,
// There is no need to set the "From" Value since it'll automatically continue from the current TranslateX Value
_thumbAnimation.To = newPos;
// Begin the animation.
_thumbStoryboard.Begin();
}
Hope that helps you :)
Regards,
Monir Abu Hilal
I have an button which I move, using a storyboard and a translateTransform :
_animatedTranslateTransform = new TranslateTransform();
this.RegisterName("slide", _animatedTranslateTransform);
DoubleAnimation slideDown = new DoubleAnimation();
slideDown.By = 20;
slideDown.Duration = TimeSpan.FromSeconds(0.5);
Storyboard.SetTargetName(slideDown, "slide");
Storyboard.SetTargetProperty(slideDown, new PropertyPath(TranslateTransform.YProperty));
After some iterations, my button have moved from 60 px, for example. How can I replace it to its initial position ?
I tried this (I set -60 to simplify the explanation) :
TranslateTransform t = (TranslateTransform) _button.RenderTransform;
t.Y = -60;
But it doesn't work if the animation already occurred once.
UPDATE:
To keep future readers from being confused by the back-and-forth below, the correct answer is to do:
_button.RenderTransform = new TranslateTransform();
Original answer:
I would store the original position to be used whenever you want to reset. I don't think there's a concept of the "original state" for a control.
It seems like it should be so simple. I've read dozens of links and I can't get anything to animate the position. I believe the closest code I can write so far is this:
Storyboard storyboard = new Storyboard();
TranslateTransform trans = new TranslateTransform() { X = 1.0, Y = 1.0 };
myCheckbox.RenderTransformOrigin = new Point(0.5, 0.5);
myCheckbox.RenderTransform = trans;
DoubleAnimation moveAnim = new DoubleAnimation();
moveAnim.Duration = TimeSpan.FromMilliseconds(1200);
moveAnim.From = -1;
moveAnim.To = 1;
Storyboard.SetTarget(moveAnim, myCheckbox);
Storyboard.SetTargetProperty(moveAnim, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
storyboard.Completed += new System.EventHandler(storyboard_Completed);
storyboard.Children.Add(moveAnim);
storyboard.Begin();
No errors are thrown.
The completion callback does get called.
If I animate opacity in a similar fashion it works fine.
How can I simply animate a UIElement's position with code??
The comment from xyzzer was correct. The cause of the confusion was because the coordinates for RenderTransformOrigin use (0,1) relative to the element. The actual transforms (e.g. TranslateTransform) use pixels as units.
I am trying to produce a path animation in WPF. It's composed of 3 points that form a triangle. And along that path is a dot that is being animated.
So far that is all working, however, it runs smoothly as the duration progresses (as you would expect!
What I would like to happen is the animation progresses incrementally, in discrete steps.
I thought I could use some kind of discrete key frame animation, but have had no luck.
So far I've got the path and the Storyboard which is (unfortunately!) working a bit too smoothly.
Is there a way to only update the animation every x seconds?
// Construct the animation path.
var pFigure = new PathFigure
{
StartPoint = pathToWalk[0],
Segments = new PathSegmentCollection
{
new LineSegment(pathToWalk[1], false),
new LineSegment(pathToWalk[2], false),
new LineSegment(pathToWalk[0], false)
}
};
var animationPath = new PathGeometry();
animationPath.Figures.Add(pFigure);
// Freeze the PathGeometry for performance
animationPath.Freeze();
// Create a PointAnimationgUsingPath to move the Dot(EllipseGeometry)
// along the animation path.
var dotAnimation = new PointAnimationUsingPath
{
PathGeometry = animationPath,
Duration = TimeSpan.FromSeconds(5),
RepeatBehavior = RepeatBehavior.Forever
};
// Set the animation to target the Center property of the
// Dot(EllipseGeometry) named "theDotToAnimate".
Storyboard.SetTargetName(dotAnimation, "theDotToAnimate");
Storyboard.SetTargetProperty(dotAnimation, new PropertyPath(EllipseGeometry.CenterProperty));
// Create a Storyboard to contain and apply the animation.
var pathAnimationStoryboard = new Storyboard
{
RepeatBehavior = RepeatBehavior.Forever,
AutoReverse = true
};
pathAnimationStoryboard.Children.Add(dotAnimation);
// Start the Storyboard when ellipsePath is loaded.
dotPath.Loaded += (sender, e) => pathAnimationStoryboard.Begin(theWindowToAddto);
I thought about getting the Animation Clock from the animation and pausing and un-pausing it in a look. That might work, but it would be the ugliest thing ever!
Can anyone help?
EDIT: I also noticed IsAdditive="True" as an option, maybe there's a way of just nudging it along a bit each time?