# How to place completely like minecraft survival or creative mode dirt blocks with this function?:

This is the functions, inside my previous scripts files:

function placeBlock() {
// Inicializar nearest_i
let nearest_i = 1;

``````// Iterar para buscar una colisión
for (let i = 10; i > 1; i -= 0.1) {
let collisionX = Math.round(camera.position.x - Math.sin(getCameraRotationY()) * Math.cos(getCameraRotationX()) * i);
let collisionY = Math.round(camera.position.y + Math.sin(getCameraRotationX()) * i);
let collisionZ = Math.round(camera.position.z - Math.cos(getCameraRotationY()) * Math.cos(getCameraRotationX()) * i);

if (!collisions["x" + collisionX + "y" + collisionY + "z" + collisionZ]) {
nearest_i = -1 / 3 + i;
break;
}
}

let blockX = Math.round(camera.position.x - Math.sin(getCameraRotationY()) * Math.cos(getCameraRotationX()) * nearest_i);
let blockY = Math.round(camera.position.y + Math.sin(getCameraRotationX()) * nearest_i);
let blockZ = Math.round(camera.position.z - Math.cos(getCameraRotationY()) * Math.cos(getCameraRotationX()) * nearest_i);

// Verificar si hay un bloque en la misma posición
let blockExists = false;
for (let block of blocks) {
if (
Math.round(block.position.x) === blockX &&
Math.round(block.position.y) === blockY &&
Math.round(block.position.z) === blockZ
) {
blockExists = true;
console.log("Returned: Block already exists in this position");
break;
}
}

// Si no hay un bloque en la misma posición, crear y añadir el bloque a la escena
if (!blockExists) {
let mesh1 = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load("bottom.jpg") }));
mesh1.position.set(blockX, blockY, blockZ);

// Marcar la posición del bloque en el objeto de colisiones
collisions["x" + blockX + "y" + blockY + "z" + blockZ] = true;

// Asegurarse de que el bloque reciba y emita sombras

// Añadir el bloque al array de bloques
blocks.push(mesh1);

console.log("Placed block at:", blockX, blockY, blockZ);
}
``````

}

The function makes a new block at some position, but if i want to craft a “+” character in this game, the player can place blocks behind the cross, which mades imposible to craft Any solution? Sorry for repeating and thanks anyway!!!

For this you would use Raycaster…

https://threejs.org/docs/#api/en/core/Raycaster

Raycaster returns an array of "hit"s [ … ] underneath the mouse.

The hit contains the object (cube) and the “normal” .normal of the hit which is a vector3 that points outwards from the face.
The normal will be -1,0,0, for the left face of the cube clicked, 1,0,0 for the right face…
0,1,0, for the top face, 0,-1,0 for the bottom face… 0,0,1 for the forward face, and 0,0,-1 for the back face.
Once you know which face was clicked, you know where direction to place the next cube.

Yeah, i marked solution because i cant delete the question…

1 Like