Create dots dynamically using the mouse

Hi everyone, it is posible create new 3D points using the mouse ??

I didn’t see any example to create dots in the 3d space.

Thank in advance to all :pray:

1 Like

Absolutely. You use the raycaster, vector for your mouse clicks and detect intersections with your model. I’ve copied this out of code of my own which loads GLTF using OrbitControls to navigate, so please shape it to fit your context.

let scene = new THREE.Scene();
let renderer = new THREE.WebGLRenderer( );
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
let camera = new THREE.PerspectiveCamera();
let loadedModel;

// NOTE loadedModel below is your model e.g. for GLTF
loader.load('yourModel.gltf', function(gltf) {
	loadedModel = gltf.scene
}

// Add click event listener to renderer's DOM element to get coordinates of viewer's click on canvas
renderer.domElement.addEventListener('click', function(event) {
	// Calculate the mouse position normalized device coordinates (NDC)
	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

	// Raycast from the camera to the clicked position
	raycaster.setFromCamera(mouse, camera);

	// Check for intersections with the model
	const modelIntersects = raycaster.intersectObject(loadedModel);

	if (modelIntersects.length > 0) {
		// Get the position of the intersection
		const intersection = modelIntersects[0].point;
		// Set marker
		setPointMarker(intersection.x,intersection.y,intersection.z)
	}
});

function setPointMarker(x,y,z){

	// properties for point marker
	const pointMarkerSphereRadius = 0.05;
	const pointMarkerSphereGeometry = new THREE.SphereGeometry(pointMarkerSphereRadius);
	const pointMarkerSphereMaterial = new THREE.MeshBasicMaterial({
	    color: 0xff00ff,
	    transparent: true,
	    opacity: 0.5
	});

	const pointMarkerSphere = new THREE.Mesh(pointMarkerSphereGeometry, pointMarkerSphereMaterial);
	
	pointMarkerSphere.position.set(x, y, z);
	
	scene.add(pointMarkerSphere);

}
2 Likes

i see thank :grinning:

1 Like

Thanks a lot :pray:

1 Like