As I delve into the world of THREE.js and explore various examples, one that caught my eye is the Voxel Painter example.
My current challenge involves ensuring that whenever a new cube is created, the roll-over mesh always moves on top of the recently placed cube rather than at the intersecting point of the current mouse position.
While the source code is accessible through the link provided, I suspect that the solution lies within the following code snippet...
Upon clicking the mouse to add a Voxel, the onMouseDown() function is triggered to determine if the current mouse position intersects with the plane and if the CTRL button has been pressed for either cube creation or deletion.
function onDocumentMouseDown( event ) {
event.preventDefault();
var intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 ) {
intersector = getRealIntersector( intersects );
// Delete cube
if ( isCtrlDown ) {
if ( intersector.object != plane ) {
scene.remove( intersector.object );
}
}
// Create cube
else {
intersector = getRealIntersector( intersects);
setVoxelPosition( intersector );
var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
voxel.position.copy( voxelPosition );
voxel.matrixAutoUpdate = false;
voxel.updateMatrix();
scene.add( voxel );
}
}
}
During the cube creation process, THREE.js captures the current point of intersection where the mouse hovers
intersector = getRealIntersector( intersects);
and then sets the new Voxel position using the function setVoxelPosition( intersector );
with the intersecting point as the input.
Here is the setVoxelPosition function...
function setVoxelPosition( intersector ) {
normalMatrix.getNormalMatrix( intersector.object.matrixWorld );
tmpVec.copy( intersector.face.normal );
tmpVec.applyMatrix3( normalMatrix ).normalize();
voxelPosition.addVectors( intersector.point, tmpVec );
voxelPosition.x = Math.floor( voxelPosition.x / 50 ) * 50 + 25;
voxelPosition.y = Math.floor( voxelPosition.y / 50 ) * 50 + 25;
voxelPosition.z = Math.floor( voxelPosition.z / 50 ) * 50 + 25;
}
And here's a snippet from the render loop...
function render() {
if ( isShiftDown )
theta += mouse2D.x * 1.5;
raycaster = projector.pickingRay( mouse2D.clone(), camera );
var intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 ) {
intersector = getRealIntersector( intersects );
if ( intersector ) {
setVoxelPosition( intersector );
rollOverMesh.position = voxelPosition;
}
}
camera.position.x = 1400 * Math.sin( THREE.Math.degToRad( theta ) );
camera.position.z = 1400 * Math.cos( THREE.Math.degToRad( theta ) );
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
I have made several attempts with different values in setVoxelPosition( intersector )
but have yet to achieve the desired outcome...
If anyone could offer guidance or point me in the right direction, it would be greatly appreciated.
Thank you.