lingo3d
Version:
Lingo3D is a React/Vue 3d game development framework that ships with a complete visual editor
80 lines • 2.82 kB
JavaScript
import nipplejs from "nipplejs";
import { joystickDefaults, joystickSchema } from "../interface/IJoystick";
import { Point } from "@lincode/math";
import createElement from "../utils/createElement";
import store, { Reactive } from "@lincode/reactivity";
import { onBeforeRender } from "../events/onBeforeRender";
import Appendable from "../display/core/Appendable";
import { onResize } from "../events/onResize";
import { uiContainer } from "../engine/renderLoop/containers";
class Joystick extends Appendable {
static componentName = "joystick";
static defaults = joystickDefaults;
static schema = joystickSchema;
static includeKeys = ["onMove"];
onMove;
onMoveStart;
onMoveEnd;
onPressState = new Reactive(undefined);
get onPress() {
return this.onPressState.get();
}
set onPress(cb) {
this.onPressState.set(cb);
}
constructor() {
super();
let pt = new Point(0, 0);
const [setDown, getDown] = store(false);
this.createEffect(() => {
const cb = this.onPressState.get();
if (!cb || !getDown())
return;
const handle = onBeforeRender(() => cb(pt));
return () => {
return handle.cancel();
};
}, [this.onPressState.get, getDown]);
const [setRefresh, getRefresh] = store({});
this.watch(onResize(() => setRefresh({})));
this.createEffect(() => {
const zone = createElement(`
<div style="width: 150px; height: 150px; position: absolute; bottom: 25px; left: 25px;"></div>
`);
uiContainer.appendChild(zone);
const prevent = (e) => {
e.preventDefault();
e.stopPropagation();
};
zone.onmousedown = prevent;
zone.ontouchstart = prevent;
zone.onpointerdown = prevent;
const manager = nipplejs.create({
zone,
mode: "static",
position: { left: "75px", bottom: "75px" },
color: "white"
});
manager.on("start", () => {
this.onMoveStart?.(new Point(0, 0));
setDown(true);
});
manager.on("move", (_, nipple) => {
this.onMove?.(nipple.vector);
pt = nipple.vector;
});
manager.on("end", () => {
pt = new Point(0, 0);
this.onMove?.(pt);
this.onMoveEnd?.(pt);
setDown(false);
});
return () => {
manager.destroy();
zone.remove();
};
}, [getRefresh]);
}
}
export default Joystick;
//# sourceMappingURL=Joystick.js.map