[英]How to do fast smooth animation in C# using WPF
我目前正在編寫Pong游戲。 我已經完成了大部分游戲,但是遇到了一個令人討厭的問題。 我使用的dispatcherTimer
的優先級設置為“發送”,時間跨度設置為1毫秒。 我正在使用高達dx = 9和dy = 9的矩形動畫,以使球足夠快地移動。 由於大的像素跳動,球出現在屏幕上跳躍而不是平穩移動。 根據數學計算,每個周期1毫秒該球的運動速度應比其快得多。 我需要更頻繁地更新球,並減少移動量...
是否有關於更好的方法的建議? 這是我所擁有的片段...
pongballTimer = new DispatcherTimer(DispatcherPriority.Send);
pongballTimer.Tick += new EventHandler(pongballTimer_Tick);
pongballTimer.Interval = new TimeSpan(0, 0, 0, 0, _balldt);
private void pongballTimer_Tick(object sender, EventArgs e)
{
double pongtop = Canvas.GetTop(PongBall);
double pongleft = Canvas.GetLeft(PongBall);
double paddletop = Canvas.GetTop( RightPaddle );
double paddleleft = Canvas.GetLeft( RightPaddle );
if (pongleft + PongBall.Width > paddleleft)
{
if (((pongtop < paddletop + RightPaddle.Height) && (pongtop > paddletop)) ||
((pongtop + PongBall.Height < paddletop + RightPaddle.Height) &&
(pongtop + PongBall.Height > paddletop)))
{
_dx *= -1;
SetBalldy(pongtop, PongBall.Height, paddletop, RightPaddle.Height);
_rightpoint++;
lblRightPoint.Content = _rightpoint.ToString();
meHitSound.Play();
}
else // The ball went past the paddle without a collision
{
RespawnPongBall(true);
_leftpoint++;
lblLeftPoint.Content = _leftpoint.ToString();
meMissSound.Play();
if (_leftpoint >= _losepoint)
LoseHappened("You Lost!!");
return;
}
}
if (pongleft < 0)
{
meHitSound.Play();
_dx *= -1;
}
if (pongtop <= _linepady ||
pongtop + PongBall.Height >= PongCanvas.Height - _linepady)
{
meDeflectSound.Play();
_dy *= -1;
}
Canvas.SetTop(PongBall, pongtop + _dy);
Canvas.SetLeft(PongBall, pongleft + _dx);
}
您可以使用WPF中內置的一種動畫技術來代替在計時器回調中進行移動。
開始閱讀《 屬性動畫技術概述》 ,也許要特別注意最后一節“ 每幀動畫:繞過動畫和定時系統” 。
然后,您可以繼續如何:使用CompositionTarget在每幀間隔上渲染 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.