// useBabylon.jsx
// Its a Context API
class BabylonInstanceEngine {
reactCanvas = null;
engine;
scene;
utilLayer;
canvas;
initialize(_canva) {
if (!_canva) return;
this.canvas = _canva;
this.engine = new Engine(this.canvas);
this.scene = new Scene(this.engine);
this.run();
if (this.scene.isReady()) {
this.camera = new ArcRotateCamera(
"camera1",
(3 * Math.PI) / 2,
-Math.PI / 2,
20,
Vector3.Zero(),
this.scene
);
this.camera.setTarget(Vector3.Zero());
this.camera.attachControl(this.canvas, true);
const light = new HemisphericLight(
"light",
new Vector3(0, 1, 0),
this.scene
);
light.intensity = 0.7;
light.diffuse = new Color3(1, 0, 0);
light.groundColor = new Color3(0, 0, 1);
light.specular = new Color3(0, 1, 0);
this.run();
} else {
console.log("Scene is not working");
}
}
run() {
if (this.engine && this.scene) {
this.engine.runRenderLoop(() => {
this.scene.render();
});
}
}
returnScene() {
return this.scene;
}
debu() {
try {
this.scene.debugLayer.show({
embedMode: true,
gizmoCamera: this.camera,
});
console.log("Inspector Working " );
} catch (error) {
console.log("Inspector Error");
}
}
This button is for creating the ground mesh in the scene
// InstanceBox.jsx
// This is a component in my project i am importing this into App.jsx to display in side panel
import { useBabylon } from "@/babylon/useBabylon";
function InstanceBox() {
const {babylonInstanceEngine,setAllMesh} = useBabylon();
return <button
className="border-2 border-[#2cead7] w-full sm:w-40 lg:w-52 p-2 sm:p-3 hover:bg-red-500 active:bg-red-700 transition duration-300"
onClick={() => {
const scene = babylonInstanceEngine.returnScene();
const ground = MeshBuilder.CreateGround(
"ground",
{ width: 6, height: 6 },
scene
);
setAllMesh((prevMesh) => [...prevMesh, ground]);
}}
>
Ground
</button>
}
export default InstanceBox;
SceneBox.jsx is contain canva
//SceneBox.jsx
import { useEffect, useRef } from "react";
import { useBabylon } from "../babylon/useBabylon";
function SceneBox() {
const { babylonInstanceEngine } = useBabylon();
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas) {
babylonInstanceEngine.initialize(canvas);
babylonInstanceEngine.run();
babylonInstanceEngine.resize();
}
}, []);
return (
<div className="w-[72%] h-screen bg-black border-[#2cead7] border-2 ">
<div className="flex flex-row justify-between px-10">
<h1 className="font-medium text-white">SceneBox</h1>
</div>
<canvas ref={canvasRef} className="w-[100%] h-[600px]" />
</div>
);
}
export default SceneBox;
App.jsx
import InstanceBox from "./components/InstanceBox";
import SceneBox from "./components/SceneBox";
function App() {
return (
<>
<div className="flex flex-row">
<InstanceBox />
<SceneBox />
</div>
</>
);
}
export default App;
Hey everyone, I just want to know if this code approach is correct. I’ve written my entire code like this, and I’m facing some issues. Before I continue, I want to ensure that everything is okay so I don’t encounter any problems later.