332 7. The Game Loop and Real-Time Simulation
while (true) // main game loop
{
// ...
// Cast a ray to see if the player has line of sight
// to the enemy.
RayCastResult r = castRay(playerPos, enemyPos);
// Now process the results...
if (r.hitSomething() && isEnemy(r.getHitObject()))
{
// Player can see the enemy.
// ...
}
// ...
}
In an asynchronous design, a ray cast request would be made by calling
a function that simply sets up and enqueues a ray cast job, and then returns
immediately. The main thread can continue doing other unrelated work while
the job is being processed by another CPU or core. Later, once the job has been
completed, the main thread can pick up the results of the ray cast query and
process them:
while (true) // main game loop
{
// ...
// Cast a ray to see if the player has line of sight
// to the enemy.
RayCastResult r;
requestRayCast(playerPos, enemyPos, &r);
// Do other unrelated work while we wait for the
// other CPU to perform the ray cast for us.
// ...
// OK, we can’t do any more useful work. Wait for the
// results of our ray cast job. If the job is
// complete, this function will return immediately.
// Otherwise, the main thread will idle until they
// are ready...
waitForRayCastResults(&r);
// Process results...
if (r.hitSomething() && isEnemy(r.getHitObject()))
{
// Player can see the enemy.
// ...
}