繁体   English   中英

如何使用WPF在C#中进行快速平滑动画

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM