Skip to content

Commit

Permalink
boilerplate playcanvas add
Browse files Browse the repository at this point in the history
  • Loading branch information
Kluskey committed Oct 9, 2024
1 parent 736b704 commit 933b96f
Showing 1 changed file with 69 additions and 10 deletions.
79 changes: 69 additions & 10 deletions mirror-2/app/space/[spaceId]/build/space-viewport.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,81 @@
"use client"

import { useGetAllEntitiesQuery } from "@/state/entities";
import { useGetAllScenesQuery } from "@/state/scenes";

import { useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import * as pc from 'playcanvas'

export default function SpaceViewport() {
const params = useParams<{ spaceId: string }>();
const canvasRef = useRef<HTMLCanvasElement | null>(null); // Create a reference for the canvas

useEffect(() => {
// Initialize PlayCanvas application
const canvas = canvasRef.current;
if (canvas) {
const app = new pc.Application(canvas, {
mouse: new pc.Mouse(canvas),
touch: new pc.TouchDevice(canvas),
});

app.start();

// Function to resize canvas based on its parent container
const resizeCanvas = () => {
const parent = canvas.parentElement;
if (parent) {
canvas.width = parent.clientWidth; // Set width based on parent
canvas.height = parent.clientHeight; // Set height based on parent
app.resizeCanvas(canvas.width, canvas.height); // Resize PlayCanvas application
}
};

// Initial resize based on the canvas's parent container size
resizeCanvas();

// Update the canvas size on window resize
window.addEventListener('resize', resizeCanvas);

// Create a camera
const camera = new pc.Entity();
camera.addComponent('camera', {
clearColor: new pc.Color(0.5, 0.5, 0.5),
});
camera.setPosition(0, 1, 5); // Position the camera
app.root.addChild(camera);

// Create a light
const light = new pc.Entity();
light.addComponent('light');
light.setEulerAngles(45, 0, 0); // Set the light angle
app.root.addChild(light);

// Create a mesh
const box = new pc.Entity();
box.addComponent('model', {
type: 'box',
});
box.setLocalPosition(0, 1, 0); // Center the mesh
app.root.addChild(box);

// Update the application
app.on("update", function (dt) {
box.rotate(10 * dt, 20 * dt, 30 * dt); // Rotate the mesh
});

// Cleanup function to remove event listeners and destroy the app on unmount
return () => {
window.removeEventListener('resize', resizeCanvas); // Clean up event listener
app.destroy(); // Destroy the PlayCanvas app
};
}
}, []);

return (
<main className="h-full">
<div
<canvas
ref={canvasRef}
className="flex h-full w-full items-center justify-center rounded-sm border border-dashed shadow-sm"
>
<h3 className="text-2xl font-bold">
3D Viewport
</h3>
</div>
style={{ width: '100%', height: '100%' }} // Ensure canvas fills the parent
/>
</main>
);
}

0 comments on commit 933b96f

Please sign in to comment.