我选择了一个如何进行游戏循环的教程,无论渲染空间有多大或CPU的速度如何,帧速率总是相同的。它涉及使用一个时间间隔,但我已经倾倒了这一百次,我不明白为什么我的版本不起作用,所以我不知道它是我的,还是他们弄错了。
原始教程可以在这里找到 http://www.dreamincode.net/forums/topic/140540-creating-games-with-c%23-part-2/
namespace TileGame
{
public partial class GameForm : Form
{
HiResTimer gameTime = new HiResTimer();
long startTime;
long interval = (long)TimeSpan.FromSeconds(1 / 30).TotalMilliseconds;
Graphics g;
Graphics imageGraphics;
Image backBuffer;
int clientWidth;
int clientHeight;
Rectangle image = new Rectangle(0, 0, 40, 50);
Point direction = new Point(1, 2);
public GameForm()
{
InitializeComponent();
this.DoubleBuffered = true;
this.MaximizeBox = false;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.ClientSize = new Size(320, 240);
clientHeight = this.ClientRectangle.Height;
clientWidth = this.ClientRectangle.Width;
backBuffer = (Image)new Bitmap(clientWidth, clientHeight);
g = this.CreateGraphics();
imageGraphics = Graphics.FromImage(backBuffer);
}
public void GameLoop()
{
gameTime.Start();
while (this.Created)
{
startTime = gameTime.ElapsedMiliseconds;
GameLogic();
Render();
Application.DoEvents();
while (gameTime.ElapsedMiliseconds - startTime < interval) ;
}
}
private void GameLogic()
{
image.X += direction.X;
image.Y += direction.Y;
if (image.X < 0)
{
image.X = 0;
direction.X *= -1;
}
if (image.Y < 0)
{
image.Y = 0;
direction.Y *= -1;
}
if (image.X + image.Width > clientWidth)
{
image.X = clientWidth - image.Width;
direction.X *= -1;
}
if (image.Y + image.Height > clientHeight)
{
image.Y = clientHeight - image.Height;
direction.Y *= -1;
}
}
private void Render()
{
imageGraphics.FillRectangle(new SolidBrush(Color.Black),
this.ClientRectangle);
imageGraphics.FillRectangle(new SolidBrush(Color.Blue), image);
this.BackgroundImage = backBuffer;
this.Invalidate();
}
}
}
答案 0 :(得分:1)
这是你的问题:
long interval = (long)TimeSpan.FromSeconds(1 / 30).TotalMilliseconds;
您正在进行整数除法,结果将为0.
修复此问题,将其转换为浮点操作:
long interval = (long)TimeSpan.FromSeconds(1 / 30.0d).TotalMilliseconds;
你的代码有其他问题,比如在while循环中忙等待,你应该让你的线程在等待时间内休眠。
答案 1 :(得分:1)
我没有在代码中看到调用GameLoop方法的任何地方。在我将30改为30d并将其添加到Form的构造函数末尾之后,您的代码为我工作了:
new Thread(GameLoop) {IsBackground = true}.Start();