Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ 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

              
                <div id="instructions">Click/touch + hold to drop more blocks.</div>

              
            
!

CSS

              
                * {
  -moz-user-select: none;  
  -ms-user-select: none;  
  -webkit-user-select: none;  
  user-select: none;

  -webkit-touch-callout: none;
}

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#instructions {
  background-color: rgba(0, 0, 0, .5);
  color: #fff;
  font-family: helvetica;
  left: 0;
  padding: 8px 16px; 
  position: absolute;
  top: 0;
}

              
            
!

JS

              
                console.clear()

class Scene extends THREE.Scene {
  #allowVibration = false
  #camera
  #controls
  #cubes = []
  #shouldDropCube = false
  #renderer
  #scene
  #timeOfLastCube
  #world

  static #INITIAL_CAMERA_TARGET = new THREE.Vector3(0, 0, 0)
  static #MIN_FORCE_FOR_CAMERA_DISTURBANCE = 5
  static #SPACE_BAR_KEY_CODE = 32
  static #FPS = 60

  constructor () {
    super()

    this.fog = new THREE.Fog(0x000000, -10 , 1024)
    this.#world = new CANNON.World()
    this.#world.gravity.set(0, -25, 0)
    this.#world.broadphase = new CANNON.NaiveBroadphase()

    this.#camera = new THREE.PerspectiveCamera(
      30,
      window.innerWidth / window.innerHeight,
      0.5,
      10000
    )
    this.#camera.position.set(0, 5, -20)
    this.#camera.lookAt(Scene.#INITIAL_CAMERA_TARGET)
    this.add(this.#camera)
    this.#makeLights()
    this.#makeFloor()
    
    // Drop first cube
    this.#makeCube()

    this.#renderer = new THREE.WebGLRenderer({ antialias: true })
    this.#renderer.setSize(window.innerWidth, window.innerHeight)
    this.#renderer.shadowMap.enabled = true
    document.body.appendChild(this.#renderer.domElement)

    const setShouldDropCube = (value, e) => {
      e.preventDefault()
      e.stopPropagation()
      this.#shouldDropCube = value
      this.#allowVibration = true
    }

    document.body.addEventListener('mousedown', setShouldDropCube.bind(this, true))
    document.body.addEventListener('mouseup', setShouldDropCube.bind(this, false))
    document.body.addEventListener('keydown', setShouldDropCube.bind(this, true))
    document.body.addEventListener('keyup', setShouldDropCube.bind(this, false))
    document.body.addEventListener('touchstart', setShouldDropCube.bind(this, true))
    document.body.addEventListener('touchend', setShouldDropCube.bind(this, false))
    window.addEventListener('selectstart', e => {
      e.preventDefault()
      return false
    })

    this.#addControls()

    this.#renderer.setAnimationLoop(this.#render)
  }

  #dumpCubes () {
    const minTimeSinceLast = 100
    const timeDiff = Date.now() - this.#timeOfLastCube

    // throttle
    if (timeDiff < minTimeSinceLast) return

    this.#makeCube()
  }

  #addControls () {
    this.#controls = new THREE.OrbitControls(
      this.#camera,
      this.#renderer.domElement
    )
    this.#controls.enablePan = false
    this.#controls.minDistance = 0
    this.#controls.maxDistance = 1500
    this.#controls.rotateSpeed = 0.5
    this.#controls.keyPanSpeed = 140
    this.#controls.listenToKeyEvents(window)
  }

  #makeCube () {
    const x = -Math.floor(Math.random() * 2000) / 1000
    const y = 8
    const z = Math.floor(Math.random() * 2000) / 1000
    const shape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5))
    const body = new CANNON.Body({ friction: 10, inertia: 1, mass: .1 })
    const geometry = new THREE.BoxGeometry(1, 1, 1)
    const material = new THREE.MeshStandardMaterial({
      color: 0x664422,
      metalness: 0,
      roughness: 1
    })
    const mesh = new THREE.Mesh(geometry, material)

    body.addShape(shape)
    body.position.set(x, y, z)
    body.quaternion.setFromAxisAngle(
      new CANNON.Vec3(1, 1, 1),
      Math.floor(Math.random() * Math.PI)
    )
    body.addEventListener('collide', this.#shakeOnCollision)
    this.#world.add(body)

    mesh.castShadow = true
    mesh.position.set(x, y, z)
    mesh.body = body
    this.#cubes.push(mesh)
    this.add(mesh)

    this.#timeOfLastCube = Date.now()
  }

  #makeFloor () {
    const geometry = new THREE.PlaneGeometry(100, 100, 1, 1)
    const material = new THREE.MeshStandardMaterial({ color: 0x001100, side: THREE.DoubleSide })
    const mesh = new THREE.Mesh(geometry, material)
    const shape = new CANNON.Plane()
    const body = new CANNON.Body({ inertia: 100, mass: 0 })

    body.addShape(shape)
    body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
    this.#world.add(body)

    mesh.castShadow = true
    mesh.quaternion.setFromAxisAngle(new THREE.Vector3(1, 0, 0), -Math.PI / 2)
    mesh.receiveShadow = true
    mesh.body = body

    this.add(mesh)
  }

  #makeLights () {
    const ambientLight = new THREE.AmbientLight(0x404040, 2)
    this.add(ambientLight)

    const light = new THREE.DirectionalLight(0xffffff, 1.75)
    const d = 100
 
    light.position.set(d, d, 0)
    light.castShadow = true
    light.shadow.mapSize.width = 1024
    light.shadow.mapSize.height = 1024
    light.shadow.camera.left = -d
    light.shadow.camera.right = d
    light.shadow.camera.top = d
    light.shadow.camera.bottom = -d
    light.shadow.camera.far = 3 * d
    light.shadow.camera.near = d
    light.shadow.darkness = 0.5

    this.add(light)
  }

  /**
   * Move the camera target on all three axes according to the force of the collision,
   * a little on x, more on y, and most on z,
   * and then quickly move it back after a short timeout.
   */
  #shakeOnCollision = e => {
    const force = e.contact.getImpactVelocityAlongNormal()

    if (force < Scene.#MIN_FORCE_FOR_CAMERA_DISTURBANCE) return

    this.#camera.lookAt(new THREE.Vector3(force / 400, force / 300, force / 50))
    setTimeout(() => this.#camera.lookAt(Scene.#INITIAL_CAMERA_TARGET), force * 3)
    
    // Vibrate API not working on mobile for some reason
    navigator.vibrate = navigator.vibrate || 
      navigator.webkitVibrate || 
      navigator.mozVibrate || 
      navigator.msVibrate
    if (navigator.vibrate && this.#allowVibration)
      navigator.vibrate(force * 10)
  }

  #render = () => {
    const dt = 1 / Scene.#FPS
    const { innerHeight, innerWidth } = window
    this.#renderer.setSize(innerWidth, innerHeight)
    this.#camera.aspect = innerWidth / innerHeight
    this.#camera.updateProjectionMatrix()

    this.#world.step(dt)

    this.#cubes.forEach(cube => {
      cube.position.copy(cube.body.position)
      cube.quaternion.copy(cube.body.quaternion)
    })

    if (this.#shouldDropCube) this.#dumpCubes()

    this.#renderer.render(this, this.#camera)
  }
}

new Scene()

              
            
!
999px

Console