Ok, so you have a UserControl (or, in my case a sprite class) up on your canvas and it looks great. Suppose something happens in your game logic and you want to animate a few parameters of your control. In my case I wanted to have a menu expand out and “spin” into the correct place over the course of 2 seconds.
Here’s a high level description of what you need to do: First, create a new StoryBoard that manages the animation. Next create a DoublAnimation class that will run the value you are changing from the From value to the To value over the time Duration. Next you need to tie everything together. The DoubleAnimation needs to be added to the storyborard and the DoubleAnimation needs to be associated with both the tag it’s working with AND the property of that tag.
The one trick comes when you try to connect the DoubleAnimation to the XAML tag. If the tag isn’t named, you can’t do it. Make sure you have a x:Name=”” for the tag holding the property you want to animate. Once you do that, the tag should show up in intelisense for the UserControl.
Here is what the code will look like if you want to animate a 180 spin of a user control:
//create a duration for the animation
Duration twoSec = new Duration(new TimeSpan(0, 0, 0, 0, 2000));
//create the new System.Windows.Controls.UserControl
rm = new GambitApps.Sprites.RadialMenu();
//put it where it belongs on the canvas.
//The -100 is to adjust for the size of the control
rm.SetValue(Canvas.TopProperty, y - 100);
rm.SetValue(Canvas.LeftProperty, x - 100);
//create the animation objects and set their start, end, and duration
DoubleAnimation spin = new DoubleAnimation();
spin.From = -180; spin.To = 0; spin.Duration = twoSec;
// now create the storyboard that we will attach to our control
Storyboard sb = new Storyboard();
// add our animation to the storyboard
sb.Children.Add(spin);
// this is where the storyboard is connected to the XAML tag we want to animate
// note that you have to x:Name the tag you want to put here
Storyboard.SetTarget(spin, rm.Rotate);
// Next, associate the DoubleAnimation class to the property type you want it to change
Storyboard.SetTargetProperty(spin, new PropertyPath(RotateTransform.AngleProperty));
// tell the storyboard to start the animation
sb.Begin();
No comments:
Post a Comment