当尝试基于Silverlight设置对象时间/帧的动画时(与使用DoubleAnimation或Storyboard不同的东西,例如不适合快节奏的游戏),例如每帧在特定方向上移动宇宙飞船,运动是跳跃的,不太顺利.屏幕甚至似乎都在撕裂.
CompositionTarget和DistpatcherTimer之间似乎没有区别.
我使用以下方法(在伪代码中):
Register Handler to Tick-Event of a DispatcherTimer In each Tick: Compute the elapsed time from the last frame in milliseconds Object.X += movementSpeed * ellapsedMilliseconds
这应该会导致运动平稳,对吧?但事实并非如此.
以下是一个示例(控件:WASD和鼠标):Silverlight Game.
虽然我所描述的效果在这个示例中并不太普遍,但我可以向您保证,即使在画布上移动单个矩形也会产生跳跃动画.
有人知道如何最小化这个.有没有其他方法可以使用Storyboards / DoubleAnimations来解决基于帧的动画问题?
编辑:这是一个快速而肮脏的方法,用最少的代码(控件:A和D)动画一个矩形Animation Sample
XAML:
<Grid x:Name="LayoutRoot" Background="Black"> <Canvas Width="1000" Height="400" Background="Blue"> <Rectangle x:Name="rect" Width="48" Height="48" Fill="White" Canvas.Top="200" Canvas.Left="0"/> </Canvas> </Grid>
C#:
private bool isLeft = false; private bool isRight = false; private DispatcherTimer timer = new DispatcherTimer(); private double lastUpdate; public Page() { InitializeComponent(); timer.Interval = TimeSpan.FromMilliseconds(1); timer.Tick += OnTick; lastUpdate = Environment.TickCount; timer.Start(); } private void OnTick(object sender,EventArgs e) { double diff = Environment.TickCount - lastUpdate; double x = Canvas.GetLeft(rect); if (isRight) x += 1 * diff; else if (isLeft) x -= 1 * diff; Canvas.SetLeft(rect,x); lastUpdate = Environment.TickCount; } private void UserControl_KeyDown(object sender,KeyEventArgs e) { if (e.Key == Key.D) isRight = true; if (e.Key == Key.A) isLeft = true; } private void UserControl_KeyUp(object sender,KeyEventArgs e) { if (e.Key == Key.D) isRight = false; if (e.Key == Key.A) isLeft = false; }
谢谢!
安德烈