Dwinzo_dev/app/src/components/ui/componets/DroppedFloatingWidgets.tsx

60 lines
1.9 KiB
TypeScript
Raw Normal View History

import { useState } from "react";
import { useThree } from "@react-three/fiber";
import * as THREE from "three";
const DroppedObjects = () => {
const { camera } = useThree(); // Now inside Canvas ✅
const [objects, setObjects] = useState<{ id: number; position: [number, number, number] }[]>([]);
// Function to convert drop event into 3D position
const handleDrop = (event: DragEvent) => {
event.preventDefault();
const data = event.dataTransfer?.getData("text/plain");
if (!data) return;
try {
const cardData = JSON.parse(data);
if (!cardData.className.includes("floating total-card")) {
console.log("Drop rejected: Incorrect element.");
return;
}
// Convert 2D drop position to 3D world coordinates
const x = (event.clientX / window.innerWidth) * 2 - 1;
const y = -(event.clientY / window.innerHeight) * 2 + 1;
// Raycasting to determine the drop position in 3D
const raycaster = new THREE.Raycaster();
const mouseVector = new THREE.Vector2(x, y);
raycaster.setFromCamera(mouseVector, camera);
// Intersect with a ground plane (assume y = 0)
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const intersection = new THREE.Vector3();
raycaster.ray.intersectPlane(groundPlane, intersection);
console.log("Spawn Object at:", intersection);
// Add the dropped object to the scene state
setObjects((prev) => [...prev, { id: Date.now(), position: [intersection.x, intersection.y, intersection.z] }]);
} catch (error) {
console.error("Invalid data:", error);
}
};
return (
<group>
{/* Render dropped objects as green boxes */}
{objects.map((obj) => (
<mesh key={obj.id} position={obj.position}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="green" />
</mesh>
))}
</group>
);
};
export default DroppedObjects;