簡體   English   中英

C# 簡單的 2d 游戲 - 制作基本的游戲循環

[英]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 FPS以使代碼“更輕”運行? 而不是嘗試生成盡可能多的幀,我懷疑這會過度使用 CPU(?)

幀率與平滑度無關。 即使您完成 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM