Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="https://unpkg.com/[email protected]/build/three.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/loaders/GLTFLoader.js"></script>
<canvas class="webgl"></canvas>
              
            
!

CSS

              
                *
{
    margin: 0;
    padding: 0;
}

html,
body
{
    overflow: hidden;
  cursor: context-menu
}

.webgl
{
    position: fixed;
    top: 0;
    left: 0;
    outline: none;
}
              
            
!

JS

              
                import * as THREE from 'https://cdn.skypack.dev/[email protected]';
import { GLTFLoader } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls.js';
console.clear()

/**
 * Base
 */

// Canvas
const canvas = document.querySelector('canvas.webgl')
// Scene
const scene = new THREE.Scene()

// Cursor
var mouse = new THREE.Vector2(),
  INTERSECTED;
var intersected;

// Raycaster
const raycaster = new THREE.Raycaster();

const radiusNumber = { counts: 3 };
const setRadius = () => {
  const rad = radiusNumber.counts + Math.random() * 12;
  return rad;
};
var material = new THREE.MeshBasicMaterial({
  color: 0x000000,
  wireframe: false,
  side: THREE.DoubleSide,
});
var material2 = new THREE.MeshBasicMaterial({
  color: 0x0000ff,
  wireframe: false,
  side: THREE.DoubleSide,
});
var wmaterial = new THREE.MeshLambertMaterial({
  color: 0xffffff,
  wireframe: true,
  transparent: true,
  opacity: 0.03,
  side: THREE.DoubleSide
});
const segments = 2;
const cubeWidth = 0.9;
const cubez = [];

let count = 200;
let rMin = 1,
  rMax = 20,
  rShift = { value: 0 };
let dummies = new Array(count).fill().map(() => {
  let d = new THREE.Object3D();

  let angle = -Math.random() * Math.PI * 2;;
  let radius = 8.5 + Math.random() * 9;

  const x = Math.cos(angle) * radius;
  const z = Math.sin(angle) * radius;

  cubez.push(d);
  d.userData = {
    dir: new THREE.Vector3()
      .random()
      .subScalar(0.5)
      .setX(x)
      .setY(0)
      .setZ(z - 2)
      .normalize(),
    dist: THREE.MathUtils.randFloat(rMin, rMax),
    scale: new THREE.Vector3(
      cubeWidth + Math.random(1 - cubeWidth),
      1 + Math.abs(Math.random(13)),
      cubeWidth + Math.random(1 - cubeWidth)
    ),
  };
  return d;
});
let geometry = new THREE.BoxGeometry(1, 1, 1, segments, segments, segments);

let cube = new THREE.InstancedMesh(geometry, material, count);


// for (let i = 0, il = cubez.length; i < il; i++) {
//   const cubeBox = new THREE.Box3().setFromArray(cubez[i]);
//   const helper = new THREE.Box3Helper(cubeBox, 0xffff00);
//   scene.add(helper);
// }
// cube.position.y = -1;
cube.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
cube.castShadow = true;
cube.receiveShadow = true;
cube.rotationValue = 0.1 + Math.abs(Math.random(8));



function updateBoxes(gltfBox) {
  dummies.forEach((d, idx) => {
    let ud = d.userData;
    d.position.copy(ud.dir).setLength(ud.dist + rShift.value);
    d.updateMatrix();
    const matrix = new THREE.Matrix4();
    matrix.setPosition(d.position);
    matrix.scale(d.userData.scale);
    cube.setMatrixAt(idx, matrix);
    cube.geometry.computeBoundingBox();
    let box = new THREE.Box3().setFromObject(cube);
    var helper = new THREE.Box3Helper(box, 0xff0000);
    box.applyMatrix4(matrix);
    helper.applyMatrix4(matrix);
    scene.add(helper);
    
    const intersectBox = box.intersectsBox(gltfBox);
    console.log('intersectBox',intersectBox);
  });
  cube.instanceMatrix.needsUpdate = true;
}

scene.add(cube);
/**
 * Lights
 */
// Ambient light
const ambientLight = new THREE.AmbientLight('#b9d5ff', 0.3)
scene.add(ambientLight)

// Directional light
const moonLight = new THREE.DirectionalLight('#b9d5ff', 0.12)
moonLight.castShadow = true
moonLight.shadow.mapSize.width = 256
moonLight.shadow.mapSize.height = 256
moonLight.shadow.camera.far = 15
moonLight.position.set(4, 5, - 2)
scene.add(moonLight)
/**
 * Sizes
 */
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
  const renderer = new THREE.WebGLRenderer({
  canvas,
});
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})
/**
 * Camera
 */
// Base camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.x = 4
camera.position.y = 2
camera.position.z = 5
scene.add(camera)

// Controls
const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true

// Model
const sceneMeshes = [];
let currentIntersect = null;
const gltfLoader = new GLTFLoader();
gltfLoader.load('https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Fox/glTF/Fox.gltf',(gltf) => {
  gltf.scene.traverse((child) => {
    gltf.scene.updateMatrixWorld(true);
    if (child.isMesh) {
      
      let m = child;
      const gltfBox = new THREE.Box3().setFromObject(m);
 
      // child.material = bakedMaterial;
      updateBoxes(gltfBox)
      const helper2 = new THREE.Box3Helper(gltfBox, 0xffff00);
      scene.add(helper2);
      sceneMeshes.push(m);
    }
     scene.add(gltf.scene);

  gltf.scene.scale.set(0.03, 0.03, 0.03);
  gltf.scene.position.set(0, -1, 0);
  gltf.scene.rotation.y = -Math.PI * 4;
  });

 
});
// Raycaster
function onMouseMove(event) {
  event.preventDefault();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

window.addEventListener("mousemove", onMouseMove, false);


updateBoxes();
/**
 * Renderer
 */
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.setClearColor('#262837')
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

/**
 * Animate
 */
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)
  
  window.addEventListener("mousemove", onMouseMove, false);

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()
              
            
!
999px

Console