[英]C# Simple 2d game - making the basic game loop
尽管我在 C# 方面有一些经验,但这是我在 C# 中的第一场比赛。 我正在尝试设置游戏的最小骨架。 我听说Tick Event
对于创建主游戏循环来说是一种糟糕的方法。
这是我试图实现的主要概念:
程序.cs
//Program.cs calls the Game Form.
Application.Run(new Game());
游戏.cs
public partial class Game : Form
{
int TotalFramesCount = 0;
int TotalTimeElapsedInSeconds = 0;
public Game()
{
InitializeComponent();
GameStart();
}
public void GameStart()
{
GameInitialize();
while(true)
{
GameUpdate();
TotalFramesCount++;
CalculateTotalTimeElapsedInSeconds();
//Have a label to display FPS
label1.text = TotalFramesCount/TotalTimeElapsedInSeconds;
}
}
private void GameInitialize()
{
//Initializes variables to create the First frame.
}
private void GameUpdate()
{
// Creates the Next frame by making changes to the Previous frame
// depending on users inputs.
}
private void CalculateTotalTimeElapsedInSeconds()
{
// Calculates total time elapsed since program started
// so that i can calculate the FPS.
}
}
现在,这将不起作用,因为while(true)
循环阻止游戏表单初始化。 我找到了一些解决方案,通过使用System.Threading.Thread.Sleep(10);
或Application.DoEvents();
,但我没能成功。
为了解释为什么我要在此处实现此代码,请使用上述代码的示例:
假设我希望我的游戏执行以下操作:
平滑地将一个100x100 Black colored Square
从(x1,y1)
点移动到(x2,y2)
然后向后循环移动,并在上述代码的label1
中显示 FPS。 考虑到上述代码,我可能会使用TotalTimeElapsedInSeconds
变量来设置与Time
相关的移动速度,而不是与Frames
,因为每台机器上的Frames
会有所不同。
// Example of fake code that moves a sqare on x axis with 20 pixels per second speed
private void GameUpdate()
{
int speed = 20;
MySquare.X = speed * TotalTimeElapsedInSeconds;
}
我之所以使用while(true)
循环,是因为我将在每台机器上获得最佳 FPS。
帧率与平滑度无关。 即使您完成 500 帧/秒,运动也会断断续续或更糟。 诀窍是与您的显示器刷新率同步。 因此,对于 60Hz 的显示器,您需要 60 帧/秒。 你不能通过在 C# 中使用循环来做到这一点。 您需要 DirectX 或 XNA。 这些框架可以将您的绘图与显示器的垂直扫描同步。
您需要为该 while(true) 循环创建自己的线程:
Thread thread = new Thread(new ThreadStart(GameStart));
thread.Priority = ThreadPriority.Lowest;
InitializeComponent();
thread.Start();
查看此博客文章以获得更多编码直觉: https : //praybook2.blogspot.com/2020/04/this-now-advanced-stuff.html
坚韧它快速循环。 使用线程有很多缺点,可以考虑使用一些现成的游戏引擎——比如 Godot; 在所有这些类型的小问题都预先修复的情况下,仅在需要时使用线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.