所以我一直在测试一些新算法,用于在 Silverlight 中创建垂直滚动游戏。我想出了一个非常简单的解决方案。但是,当您在手机上运行它时,会出现大量帧速率不一致的情况。我不知道这是否是由于算法不佳,一次绘制很多东西(目前只有 png 背景和股票播放器图像)或其他原因。
本质上,我想要的是一个游戏循环计时器,它执行一个方法,我可以从中执行所有更新方法,并且无论您在游戏的哪个部分,都具有一致的外观和感觉。这是后端代码。
public partial class MainPage : PhoneApplicationPage
{
// Constructor
int counter = 0;
DispatcherTimer playerTimer;
string _START = "START";
string _FALLING = "FALLING";
string _LEFT = "LEFT";
string _RIGHT = "RIGHT";
string _CENTER = "CENTER";
string playerState = "";
int playerMoveTimeout = 20;
public MainPage()
{
InitializeComponent();
playerState = _START;
playerTimer = new DispatcherTimer();
playerTimer.Interval = TimeSpan.FromSeconds(.00999);
playerTimer.Tick += playerTimer_Tick;
playerTimer.Start();
}
void playerTimer_Tick(object sender, EventArgs e)
{
updatePlayer();
if (counter > 0)
{
counter = updateBG(counter);
}
}
public void updatePlayer()
{
if (Canvas.GetLeft(Player) + Player.Width >= 480)
{
playerState = _LEFT;
}
else if (Canvas.GetLeft(Player) <= 0)
{
playerState = _RIGHT;
}
if(playerMoveTimeout <= 0)
{
playerState = _FALLING;
}
if (playerState.Equals(_START))
{ }
else if (playerState.Equals(_FALLING))
{
Canvas.SetTop(Player, Canvas.GetTop(Player) + 30);
}
else if (playerState.Equals(_LEFT))
{
Canvas.SetTop(Player, Canvas.GetTop(Player) - 60);
Canvas.SetLeft(Player, Canvas.GetLeft(Player) - 20);
playerMoveTimeout--;
}
else if (playerState.Equals(_RIGHT))
{
Canvas.SetTop(Player, Canvas.GetTop(Player) - 60);
Canvas.SetLeft(Player, Canvas.GetLeft(Player) + 20);
playerMoveTimeout--;
}
else //CENTER
{
Canvas.SetTop(Player, Canvas.GetTop(Player) - 60);
playerMoveTimeout--;
}
}
public int updateBG(int time)
{
if (Canvas.GetTop(background) > 800)
Canvas.SetTop(background, -2400);
int x = time;
Canvas.SetTop(background, Canvas.GetTop(background) + 60);
x -= 40;
return x;
}
private void Player_Tap(object sender, GestureEventArgs e)
{
Point point = e.GetPosition(Player);
double Y = point.Y;
double X = point.X;
if (X < 80)
{
counter = 400;
playerMoveTimeout = 20;
playerState = _RIGHT;
}
else if (X > 120)
{
counter = 400;
playerMoveTimeout = 20;
playerState = _LEFT;
}
else
{
counter = 400;
playerMoveTimeout = 20;
playerState = _CENTER;
}
}
}