I'm currently in the process of making a game loop in a console application. I'm trying to make the game loop wait at the end of its loop for (1000*10000/fps) - ElapsedTicks
to put a cap on game loop speed. For reference 1 millisecond is 10,000 ticks.
If the ElapsedTicks < FrameTimeTicks
I execute await Task.Delay(FrameTimeTicks - ElapsedTicks)
but this ends my console application.
The code responsible is the await Task.Delay so I assume I'm not using it properly.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApp1
{
class Program
{
static byte fps = 30;
public static byte Fps { get { return fps; } set { fps = value; } }
//user specified fps
static long frameTimeTicks = (1000 * 10000) / Fps;
static long FrameTimeTicks { get { return frameTimeTicks; } }
//amount of ticks desired in one frame
static bool draw = true;
public static bool Draw { get { return draw; } set { draw = value; } }
static long elapsedTicks;
static long ElapsedTicks { get { return elapsedTicks; } set { elapsedTicks = value; } }
//ticks elapsed in one game loop
static void Main(string[] args)
{
GameLoop();
}
static void UpdateGame()
{
int a = 0;
a++;
}
static void Render()
{
Console.WriteLine("@");
}
public static async void GameLoop()
{
Stopwatch gameLoopTicks = Stopwatch.StartNew();
while (true)
{
gameLoopTicks.Restart();
if (Console.KeyAvailable == true)
{
char KeyPressed = Console.ReadKey().KeyChar;
}
UpdateGame();
if (Draw == true)
{
Render();
}
ElapsedTicks = gameLoopTicks.ElapsedTicks;
if (ElapsedTicks > FrameTimeTicks)
{
Draw = false;
}
else
{
Draw = true;
await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
}
}
}
}
}
I Have also tried this variation but to the same result, my console application ends.
public static async void GameLoop()
{
Stopwatch gameLoopTicks = Stopwatch.StartNew();
async Task PauseGameLoop()
{
//Console.ReadKey(); execution ends here!
await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
GameLoop();
}
while (true)
{
gameLoopTicks.Restart();
if (Console.KeyAvailable == true)
{
char KeyPressed = Console.ReadKey().KeyChar;
}
UpdateGame();
if (Draw == true)
{
Render();
}
ElapsedTicks = gameLoopTicks.ElapsedTicks;
if (ElapsedTicks > FrameTimeTicks)
{
Draw = false;
}
else
{
Draw = true;
await PauseGameLoop();
}
}
Task.Delay MSDN, await MSDN. Am I tackling this problem the wrong way ? This post is why I chose this method. Thanks for the help!