C# Update Loop

Started by
1 comment, last by Ultraporing 1 year, 2 months ago

So I've made AI thread and its working good except the movement. Main thread and AI thread are both on 60fps (testing stuff) and if I put AI on AI thread it does not always move smoothly it kinda vibrates sometimes (the units look like they vibrate while moving sometimes) /

Here is that AI thread :

private Stopwatch stopwatch;

private const double TargetFPS = 60.0;

private const double TargetFrameTime = 1.0 / TargetFPS;

public void UpdateAI()

{

stopwatch = Stopwatch.StartNew();

while (true)

{

double elapsedSeconds = stopwatch.Elapsed.TotalSeconds;

stopwatch.Restart();

for (int i = 0; i < aiList.Count; i++)

{

if (IsInstanceValid(aiList[i]))

{

aiList[i].Update((float)elapsedSeconds);

}

else

{

aiList.RemoveAt(i);

}

}

double frameTime = stopwatch.Elapsed.TotalSeconds;

double sleepTime = TargetFrameTime - frameTime;

if (sleepTime > 0)

{

System.Threading.Thread.Sleep((int)(sleepTime * 1000));

}

}

}

Now can someone tell me if this is correctly capped at 60 fps? Also how would I measure fps here?

Thanks in advance.

Ayy lmao

Advertisement

Hi, a simple method to measure fps is counting until you reach 1 second. But why the AI vibrates I can't say for sure without knowing how you move them. Regarding if it's capped properly, it seems so the fps counter tells me 60 fps.

Add a double variable to track the total elapsed time. And add an int variable for your fps.
initialize both to 0 at the start of updateAi. I'll add some code snippets.
I check if total is 1 or bigger right after the stopwatch reset. And add the sleeptime and frame time right before the sleep if statement, and at the end we increment the fps counter.

...
stopwatch.Restart();
...
if (tot >= 1.0)
{
	Console.WriteLine("fps " + fpss);
	fpss = 0; // fps measured
	tot = 0; // total elapsed
}
...
tot += sleepTime + frameTime;
if (sleepTime > 0)
{
	System.Threading.Thread.Sleep((int)(sleepTime * 1000.0));
}

fpss++;

“It's a cruel and random world, but the chaos is all so beautiful.”
― Hiromu Arakawa

This topic is closed to new replies.

Advertisement