Game AI Algorithms
C
#include <time.h>
typedef struct {
double x, speed;
} NPC;
void update(NPC *npc, double target, double dt) {
double distance = target - npc->x;
double step = npc->speed * dt;
if (distance > step) npc->x += step;
else if (distance < -step) npc->x -= step;
else npc->x = target;
}
double seconds(void) {
struct timespec t;
timespec_get(&t, TIME_UTC);
return (double)t.tv_sec + t.tv_nsec / 1e9;
}
int main(void) {
NPC npc = {0, 2}; // Position 0; speed 2 units/second.
double target = 10;
double previous = seconds();
int running = 1;
while (running) {
double now = seconds();
double dt = now - previous;
previous = now;
// Read input; set running = 0 to quit.
update(&npc, target, dt);
// Draw the game.
}
return 0;
}
JavaScript
const npc = { x: 0, speed: 2 };
function update(npc, target, dt) {
const distance = target - npc.x;
const step = npc.speed * dt;
if (distance > step) npc.x += step;
else if (distance < -step) npc.x -= step;
else npc.x = target;
}
const target = 10;
let previous = performance.now();
let running = true;
function loop(now) {
if (!running) return;
const dt = (now - previous) / 1000;
previous = now;
// Read input; set running = false to quit.
update(npc, target, dt);
// Draw the game.
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Nim
import std/[monotimes, os]
type NPC = object
x, speed: float
proc update(npc: var NPC, target, dt: float) =
let distance = target - npc.x
let step = npc.speed * dt
if distance > step: npc.x += step
elif distance < -step: npc.x -= step
else: npc.x = target
var npc = NPC(x: 0, speed: 2)
let target = 10.0
var previous = getMonoTime()
var running = true
while running:
let now = getMonoTime()
let dt = float(now.ticks - previous.ticks) / 1_000_000_000.0
previous = now
# Read input; set running = false to quit.
update(npc, target, dt)
# Draw the game.
sleep(1)
← All snippets