Skip to content

Instantly share code, notes, and snippets.

@shivaduke28
Last active December 12, 2023 13:37
Show Gist options
  • Save shivaduke28/3ed7dc742dbd4ab5ccac49b842d2965c to your computer and use it in GitHub Desktop.
Save shivaduke28/3ed7dc742dbd4ab5ccac49b842d2965c to your computer and use it in GitHub Desktop.
cluster item script for delay, interval, cancel.
const cid = () => Math.floor(Math.random() * 1e4);
const delay = (t, f, a) => {
let i = cid();
let l = $.state.l ?? [];
l.push([i, t, f.name, a]);
$.state.l = l;
return i;
};
const interval = (t, f, a) => {
let i = cid();
let l = $.state.l ?? [];
l.push([i, t, f.name, a, t]);
$.state.l = l;
return i;
};
const cancel = i => {
let lc = $.state.lc ?? [];
lc.push(i);
$.state.lc = lc;
};
const tick = t => {
let l = $.state.l;
if (!l) return;
let lc = $.state.lc;
$.state.l = [];
$.state.lc = null;
l.forEach(c => {
if (lc && lc.indexOf(c[0]) >= 0) {
c[1] = -1;
} else if ((c[1] > 0) && (c[1] -= t, c[1] <= 0)) {
if (c.length > 4) c[1] = c[4];
try { this[c[2]](c[3]) }
catch { c[1] = -1 }
}
});
$.state.l = l.filter(c => c[1] > 0).concat($.state.l);
};
$.onUpdate(t => {
tick(t);
});
$.onInteract(p => {
cancel($.state.i);
cancel($.state.j);
$.state.p = p;
$.state.i = interval(0.5, foo, 2);
$.state.j = delay(4, bar);
});
// use not 'const foo() =>{}' but 'function' to call it by 'this["foo"]()'
function foo(v) {
$.state.p.addVelocity(new Vector3(0, v, 0));
};
function bar() {
delay(0.5, foo, 10);
cancel($.state.i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment