@playcanvas/react
Version:
A React renderer for PlayCanvas – build interactive 3D applications using React's declarative paradigm.
48 lines • 1.97 kB
JavaScript
import { Script as PcScript } from "playcanvas";
import { useScript } from "../hooks/index.js";
import { forwardRef, memo, useMemo } from "react";
import { validatePropsPartial } from "../utils/validation.js";
import { shallowEquals } from "../utils/compare.js";
/**
* The Script component allows you to hook into the entity's lifecycle. This allows you to
* run code during the frame update loop, or when the entity is created or destroyed.
* Use this for high-performance code that needs to run on every frame.
*
* @param {ScriptProps} props - The props to pass to the script component.
* @see https://api.playcanvas.com/engine/classes/Script.html
* @example
* // A Rotator script that rotates the entity around the Y axis
* class Rotator extends Script {
* static scriptName = 'rotator';
*
* update(dt: number) {
* this.entity.rotate(0, 1, 0, dt);
* }
* }
* <Script script={Rotator} />
*/
const ScriptComponent = forwardRef(function ScriptComponent(props, ref) {
const validatedProps = validatePropsPartial(props, componentDefinition, false);
const { script, ...restProps } = validatedProps;
const memoizedProps = useMemo(() => restProps, [restProps]);
useScript(script, memoizedProps, ref);
return null;
});
// Memoize the component to prevent re-rendering if `script` or `props` are the same
export const Script = memo(ScriptComponent, (prevProps, nextProps) => {
return prevProps.script === nextProps.script && shallowEquals(prevProps, nextProps);
});
class NullScript extends PcScript {
}
const componentDefinition = {
name: "Script",
apiName: "ScriptComponent",
schema: {
script: {
validate: (value) => Boolean(value && value instanceof Function && value.prototype instanceof PcScript),
errorMsg: (value) => `Invalid value for prop "script": "${value}". Expected a subclass of Script.`,
default: NullScript
}
}
};
//# sourceMappingURL=Script.js.map