Skip to content

Commit

Permalink
fix: fast loop using update (#513)
Browse files Browse the repository at this point in the history
  • Loading branch information
dragoncoder047 authored and lajbel committed Nov 23, 2024
1 parent 2f850d0 commit ed8c4e1
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 45 deletions.
44 changes: 44 additions & 0 deletions examples/fastLoop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// @ts-check

kaplay();

loadBean();

const interval = 0.001;
const delay = 1;

loop(interval, () => {
const bean = add([
sprite("bean"),
pos(rand(vec2(0), vec2(width(), height()))),
]);
wait(delay, () => {
destroy(bean);
});
}, -1, true);

const counter = add([
pos(10, 10),
text(""),
z(9999),
]);
add([
pos(counter.pos),
rect(counter.width, counter.height),
color(BLACK),
z(counter.z - 1),
{
update() {
this.width = counter.width;
this.height = counter.height;
}
}
])

var beanCount = 0;
onAdd(() => beanCount++);
onDestroy(() => beanCount--);
loop(0.1, () => {
const error = 100 * Math.abs((delay / interval) - beanCount) / (delay / interval);
counter.text = `${beanCount.toFixed().padStart(5)} beans\nerror: ${error.toFixed(2).padStart(5)}%`;
});
77 changes: 34 additions & 43 deletions src/components/misc/timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,32 @@ import type {
TimerController,
TweenController,
} from "../../types";
import type { KEventController } from "../../utils";
import { KEvent } from "../../utils";

/**
* The {@link timer `timer()`} component.
*
* @group Component Types
*/
export interface TimerComp extends Comp {
/**
* The maximum number of loops per frame allowed,
* to keep loops with sub-frame intervals from freezing the game.
*/
maxLoopsPerFrame: number
/**
* Run the callback after n seconds.
*/
wait(time: number, action?: () => void): TimerController;
/**
* Run the callback every n seconds.
*
* If waitFirst is false (the default), the function will
* be called once on the very next frame, and then loop like normal.
*
* @since v3000.0
*/
loop(time: number, action: () => void): KEventController;
loop(time: number, action: () => void, maxLoops?: number, waitFirst?: boolean): TimerController;
/**
* Tweeeeen! Note that this doesn't specifically mean tweening on this object's property, this just registers the timer on this object, so the tween will cancel with the object gets destroyed, or paused when obj.paused is true.
*
Expand All @@ -40,59 +48,42 @@ export interface TimerComp extends Comp {
): TweenController;
}

export function timer(): TimerComp {
export function timer(maxLoopsPerFrame: number = 1000): TimerComp {
return {
id: "timer",
wait(
this: GameObj<TimerComp>,
time: number,
action?: () => void,
): TimerController {
const actions: Function[] = [];

if (action) actions.push(action);
let t = 0;
maxLoopsPerFrame,
loop(this: GameObj<TimerComp>, time: number, action: () => void, count: number = -1, waitFirst: boolean = false): TimerController {
let t: number = waitFirst ? 0 : time;
let onEndEvents = new KEvent;
const ev = this.onUpdate(() => {
t += _k.app.state.dt;
if (t >= time) {
actions.forEach((f) => f());
ev.cancel();
for (let i = 0; t >= time && i < this.maxLoopsPerFrame; i++) {
if (count != -1) {
count--;
if (count < 0) {
ev.cancel();
onEndEvents.trigger();
return;
}
}
action();
t -= time;
}
});
})
return {
get paused() {
return ev.paused;
return ev.paused
},
set paused(p) {
ev.paused = p;
ev.paused = p
},
cancel: ev.cancel,
onEnd(action) {
actions.push(action);
},
then(action) {
this.onEnd(action);
return this;
},
};
onEnd: onEndEvents.add,
then(f) { onEndEvents.add(f); return this; }
}
},
loop(t: number, action: () => void): KEventController {
let curTimer: null | TimerController = null;
const newAction = () => {
// TODO: should f be execute right away as loop() is called?
curTimer = this.wait(t, newAction);
action();
};
curTimer = this.wait(0, newAction);
return {
get paused() {
return curTimer?.paused ?? false;
},
set paused(p) {
if (curTimer) curTimer.paused = p;
},
cancel: () => curTimer?.cancel(),
};
wait(this: GameObj<TimerComp>, time: number, action?: () => void): TimerController {
return this.loop(time, action ?? (() => { }), 1, true);
},
tween<V extends LerpValue>(
this: GameObj<TimerComp>,
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,7 @@ export interface KAPLAYCtx<
*
* @group Components
*/
timer(): TimerComp;
timer(maxLoopsPerFrame?: number): TimerComp;
/**
* Make object unaffected by camera or parent object transforms, and render at last.
*
Expand Down Expand Up @@ -2691,7 +2691,7 @@ export interface KAPLAYCtx<
* ```
* @group Timer
*/
loop(t: number, action: () => void): KEventController;
loop(t: number, action: () => void, maxLoops?: number, waitFirst?: boolean): TimerController;
/**
* Play a piece of audio.
*
Expand Down

0 comments on commit ed8c4e1

Please sign in to comment.