UNPKG

pixi-fusion

Version:

This module offers a set of common components needed for playing games.

75 lines (74 loc) 2.08 kB
import React, { createContext, useEffect, useMemo, useRef, useState } from "react"; import { Engine, Runner, World } from "matter-js"; export const MatterPhysicsContext = createContext({ config: { world: { width: 480, height: 320 } }, engine: Engine.create(), runner: Runner.create(), run: () => { }, stop: () => { }, addBody: () => { }, removeBody: () => { } }); export const MatterPhysicsContextProvider = ({ isRunning = false, children, config = { world: { width: 480, height: 320 } } }) => { const isRunningRef = useRef(false); const [localConfig] = useState(config); const world = useMemo(() => { return World.create({ bounds: { min: { x: 0, y: 0 }, max: { x: config.world.width, y: config.world.height } } }); }, [config.world]); const engine = useMemo(() => { return Engine.create({ world }); }, [world]); const runner = useMemo(() => Runner.create(), []); const addBody = (body) => { if (engine?.world) { World.add(engine?.world, body); } }; const removeBody = (body) => { if (engine?.world) { World.remove(engine?.world, body); } }; const run = () => { if (!isRunningRef.current) { Runner.run(runner, engine); isRunningRef.current = true; } }; const stop = () => { if (isRunningRef.current) { Runner.stop(runner); isRunningRef.current = false; } }; const conextValue = useMemo(() => ({ config: localConfig, runner, engine, run, stop, addBody, removeBody }), [runner, engine, localConfig]); useEffect(() => { if (isRunning) { run(); } return () => { stop(); }; }, [isRunning]); return React.createElement(MatterPhysicsContext.Provider, { value: conextValue }, children); };