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="info">
  <div id="notice">click anywhere for sound</div>
  <div class="highlight"><span id="precision">3</span> decimal <span id="precision-place-noun-form">places</span> expected</div>
  <div class="highlight">explanation in pen details</div>
  <div>m₁ = 1 ; v₁ ≈ <span id="velocity-1">0</span></div>
  <div>m₂ = <span id="mass-2">1000000</span> ; v₂ ≈ <span id="velocity-2">0</span></div>
  <div>t = <span id="time">0.0</span> s</div>
  <div>π = <span id="pi">3.141592…</span></div>
  <div>n<sub>collisions</sub> = <span id="n-collisions">0</span></div>
</div>
              
            
!

CSS

              
                body {
  background: #000;
  overflow-x: hidden;
}

sub {
  font-size: 0.5em;
}

#info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 21ch;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  font: bold 1rem "SF Mono", "Menlo", "Roboto Mono", "Consolas", monospace;
  white-space: nowrap;
  @media screen and (min-width: 28rem) and (min-height: 28rem) {
    font-size: 1.5rem;
  }
}

#notice {
  font-style: italic;
}

#instruction {
  animation: blink 2s step-end infinite;
}

.highlight {
  color: #e61d5f;
}

@keyframes blink {
  0% {
    opacity: 1;
  }
  50%, 100% {
    opacity: 0;
  }
}
              
            
!

JS

              
                // PARAMETERS

const simulation = {
  threeD: true,
  clicked: false,
  soundVolume: 0,
  massTwoExponent: 3,
  cubeOne: {
    initialVelocityValue: 100,
    initialDistanceFromWall: 50,
    mass: 100,
    size: 100
  },
  cubeTwo: {
    initialVelocityValue: 100,
    initialDistanceFromCubeOne: 50,
    mass: 100,
    size: 100
  },
  calculatePhysics: true
}

// CORE

let collisions = []
let collisionHandlers = []

const clock = new THREE.Clock()

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.gammaOutput = true
renderer.domElement.style.display = 'block'

const scene = new THREE.Scene()

let screenWidth = innerWidth
let screenHeight = innerHeight

function render() {
  requestAnimationFrame(render)
  const delta = clock.getDelta()
  cubeOneMixer.update(delta)
  cubeTwoMixer.update(delta)
  info.time.innerHTML = cubeOneMixer.time.toFixed(1)
  renderer.render(scene, simulation.threeD ? perspectiveCamera : orthographicCamera)
  stats.update()
}

// CAMERAS

const orthographicCamera = new THREE.OrthographicCamera(0, screenWidth, screenHeight / 2, screenHeight / -2, 1, 2000000)
orthographicCamera.position.z = 1000

const perspectiveCamera = new THREE.PerspectiveCamera(45, screenWidth / screenHeight, 1, 2000000)
perspectiveCamera.position.x = 500
perspectiveCamera.position.y = 250
perspectiveCamera.position.z = 1000

const perspectiveCameraControls = new THREE.OrbitControls(perspectiveCamera, renderer.domElement)

// SCREEN SIZE HANDLING

function updateScreen() {
  screenWidth = innerWidth
  screenHeight = innerHeight
  renderer.setPixelRatio(devicePixelRatio)
  renderer.setSize(screenWidth, screenHeight)
  if (simulation.threeD) {
    perspectiveCamera.aspect = screenWidth / screenHeight
    perspectiveCamera.updateProjectionMatrix()
  } else {
    orthographicCamera.right = screenWidth
    orthographicCamera.top = screenHeight / 2
    orthographicCamera.bottom = -screenHeight / 2
    orthographicCamera.updateProjectionMatrix()
  }
}

// INFO DISPLAY

const info = {
  container: document.getElementById('info'),
  precision: document.getElementById('precision'),
  precisionPlaceNounForm: document.getElementById('precision-place-noun-form'),
  velocityOne: document.getElementById('velocity-1'),
  velocityTwo: document.getElementById('velocity-2'),
  massTwo: document.getElementById('mass-2'),
  time: document.getElementById('time'),
  pi: document.getElementById('pi'),
  collisionCounter: document.getElementById('n-collisions')
}

// SOUND

const bumpSound = new Howl({
  src: 'https://res.cloudinary.com/twixes/video/upload/v1549902093/808.wav'
})

function updateVolume() {
  Howler.volume(simulation.soundVolume)
}

// LIGHT

const ambientLight = new THREE.HemisphereLight(0x666666)
scene.add(ambientLight)

const directionalLight = new THREE.DirectionalLight(0xffffff)
directionalLight.position.set(500, 1000, 1500)
directionalLight.castShadow = true
directionalLight.shadow.camera.left = -100
directionalLight.shadow.camera.right = 5900
directionalLight.shadow.camera.top = 400
directionalLight.shadow.camera.bottom = -1200
directionalLight.shadow.mapSize.width = 8192
directionalLight.shadow.mapSize.height = 4096
directionalLight.shadow.camera.near = 1
directionalLight.shadow.camera.far = 22000
scene.add(directionalLight)
/* light helper
const directionalLightShadowCameraHelper = new THREE.CameraHelper(directionalLight.shadow.camera)
scene.add(directionalLightShadowCameraHelper) */

// GEOMETRY

const wallGeometry = new THREE.CircleGeometry(20000, 100)
const wallFrontMaterial = new THREE.MeshStandardMaterial({ color: 0x0000ff, roughness: 1 })
const wallFront = new THREE.Mesh(wallGeometry, wallFrontMaterial)
wallFront.receiveShadow = true
wallFront.rotation.y = Math.PI / 2
wallFront.matrixAutoUpdate = false
wallFront.updateMatrix()
scene.add(wallFront)
const wallBackMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 1 })
const wallBack = new THREE.Mesh(wallGeometry, wallBackMaterial)
wallBack.receiveShadow = true
wallBack.rotation.y = 3 * Math.PI / 2
wallBack.matrixAutoUpdate = false
wallBack.updateMatrix()
scene.add(wallBack)

const cubeGeometry = new THREE.BoxGeometry()
const cubeOneMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 })
const cubeOne = new THREE.Mesh(cubeGeometry, cubeOneMaterial)
cubeOne.castShadow = true
cubeOne.receiveShadow = true
scene.add(cubeOne)
const cubeOneMixer = new THREE.AnimationMixer(cubeOne)
const cubeTwoMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 1 })
const cubeTwo = new THREE.Mesh(cubeGeometry, cubeTwoMaterial)
cubeTwo.castShadow = true
cubeTwo.receiveShadow = true
scene.add(cubeTwo)
const cubeTwoMixer = new THREE.AnimationMixer(cubeTwo)

// CONTROL

simulation.reset = () => {
  cubeOneMixer.stopAllAction()
  cubeTwoMixer.stopAllAction()
  simulation.cubeOne.mass = 1
  simulation.cubeTwo.mass = 100 ** simulation.massTwoExponent
  cubeOne.scale.set(simulation.cubeOne.size, simulation.cubeOne.size, simulation.cubeOne.size)
  cubeTwo.scale.set(simulation.cubeTwo.size, simulation.cubeTwo.size, simulation.cubeTwo.size)
  cubeOne.position.x = simulation.cubeOne.initialDistanceFromWall + simulation.cubeOne.size / 2
  cubeTwo.position.x = simulation.cubeOne.initialDistanceFromWall + simulation.cubeOne.size + simulation.cubeTwo.initialDistanceFromCubeOne + simulation.cubeTwo.size / 2
  info.precision.innerHTML = simulation.massTwoExponent
  info.precisionPlaceNounForm.innerHTML = Math.abs(simulation.massTwoExponent) === 1 ? 'place' : 'places'
  info.massTwo.innerHTML = 100 ** simulation.massTwoExponent
  info.pi.className = ''
  info.collisionCounter.className = ''
  info.collisionCounter.innerHTML = '0'
}

simulation.playReset = () => {
  simulation.reset()
  const cubeOneVelocity = Math.round(-simulation.cubeOne.initialVelocityValue)
  const cubeTwoVelocity = Math.round(-simulation.cubeTwo.initialVelocityValue)
  info.velocityOne.innerHTML = cubeOneVelocity > 0 ? '+' + cubeOneVelocity : cubeOneVelocity
  info.velocityTwo.innerHTML = cubeTwoVelocity > 0 ? '+' + cubeTwoVelocity : cubeTwoVelocity
  info.container.style.width = `${Math.max(18 + 2 * simulation.massTwoExponent, 26)}ch` // adjust info container width
  if (simulation.calculatePhysics) {
    collisions = [...calculateCollisions()]
    simulation.calculatePhysics = false
  }
  animatePhysics()
}

simulation.playResetWithRecalculation = () => {
  simulation.calculatePhysics = true
  simulation.playReset()
}

// PHYSICS

function* calculateCollisions() {
  let previousCollision = {
    number: 0,
    time: 0,
    cubeOneX: simulation.cubeOne.initialDistanceFromWall + simulation.cubeOne.size / 2,
    cubeOneVelocity: -simulation.cubeOne.initialVelocityValue,
    cubeTwoX: simulation.cubeOne.initialDistanceFromWall + simulation.cubeOne.size + simulation.cubeTwo.initialDistanceFromCubeOne + simulation.cubeTwo.size / 2,
    cubeTwoVelocity: -simulation.cubeTwo.initialVelocityValue
  }
  let last
  while (!last) {
    yield previousCollision
    last = false
    let thisCollision = {
      number: null,
      time: null,
      cubeOneX: null,
      cubeOneVelocity: null,
      cubeTwoX: null,
      cubeTwoVelocity: null
    }
    let deltaTimeCubeOneVsWall
    if (previousCollision.cubeOneVelocity < 0) {
      deltaTimeCubeOneVsWall = -(previousCollision.cubeOneX - simulation.cubeOne.size / 2) / previousCollision.cubeOneVelocity
    } else {
      deltaTimeCubeOneVsWall = Infinity
    }
    let deltaTimeCubeOneVsCubeTwo
    if (
      (previousCollision.cubeOneVelocity > 0 && previousCollision.cubeOneVelocity > previousCollision.cubeTwoVelocity) ||
      (previousCollision.cubeTwoVelocity < 0 && previousCollision.cubeOneVelocity > previousCollision.cubeTwoVelocity)
    ) {
      deltaTimeCubeOneVsCubeTwo = (previousCollision.cubeOneX + simulation.cubeOne.size / 2 - previousCollision.cubeTwoX + simulation.cubeTwo.size / 2) / (previousCollision.cubeTwoVelocity - previousCollision.cubeOneVelocity)
    } else {
      deltaTimeCubeOneVsCubeTwo = Infinity
    }
    let deltaNumber = 0
    let deltaTime = 600
    if (deltaTimeCubeOneVsCubeTwo < Infinity || deltaTimeCubeOneVsWall < Infinity) {
      deltaNumber = 1
      if (deltaTimeCubeOneVsWall < deltaTimeCubeOneVsCubeTwo) {
        deltaTime = deltaTimeCubeOneVsWall
        thisCollision.cubeOneVelocity = -previousCollision.cubeOneVelocity
        thisCollision.cubeTwoVelocity = previousCollision.cubeTwoVelocity
      } else if (deltaTimeCubeOneVsWall > deltaTimeCubeOneVsCubeTwo) {
        deltaTime = deltaTimeCubeOneVsCubeTwo
        thisCollision.cubeOneVelocity = (
          (simulation.cubeOne.mass - simulation.cubeTwo.mass) / (simulation.cubeOne.mass + simulation.cubeTwo.mass) * previousCollision.cubeOneVelocity +
          2 * simulation.cubeTwo.mass / (simulation.cubeOne.mass + simulation.cubeTwo.mass) * previousCollision.cubeTwoVelocity
        )
        thisCollision.cubeTwoVelocity = (
          2 * simulation.cubeOne.mass / (simulation.cubeOne.mass + simulation.cubeTwo.mass) * previousCollision.cubeOneVelocity +
          (simulation.cubeTwo.mass - simulation.cubeOne.mass) / (simulation.cubeOne.mass + simulation.cubeTwo.mass) * previousCollision.cubeTwoVelocity
        )
      } else {
        deltaNumber = 2
        deltaTime = deltaTimeCubeOneVsWall
        thisCollision.cubeOneVelocity = -previousCollision.cubeOneVelocity
        thisCollision.cubeTwoVelocity = -previousCollision.cubeTwoVelocity
      }
    } else {
      last = true
    }
    thisCollision.number = previousCollision.number + deltaNumber
    thisCollision.time = previousCollision.time + deltaTime
    thisCollision.cubeOneX = previousCollision.cubeOneX + previousCollision.cubeOneVelocity * deltaTime
    thisCollision.cubeTwoX = previousCollision.cubeTwoX + previousCollision.cubeTwoVelocity * deltaTime
    previousCollision = thisCollision
  }
  yield previousCollision
}

function animatePhysics() {
  const times = []
  const cubeOneValues = []
  const cubeTwoValues = []
  for (const collision of collisions) {
    times.push(collision.time)
    cubeOneValues.push(collision.cubeOneX)
    cubeTwoValues.push(collision.cubeTwoX)
  }
  const cubeOneTrack = new THREE.NumberKeyframeTrack('cubeOne.position[x]', times, cubeOneValues)
  const cubeTwoTrack = new THREE.NumberKeyframeTrack('cubeTwo.position[x]', times, cubeTwoValues)
  const cubeOneClip = new THREE.AnimationClip('cubeOneMotion', times[times.length - 1], [cubeOneTrack])
  const cubeTwoClip = new THREE.AnimationClip('cubeTwoMotion', times[times.length - 1], [cubeTwoTrack])
  const cubeOneAction = cubeOneMixer.clipAction(cubeOneClip)
  const cubeTwoAction = cubeTwoMixer.clipAction(cubeTwoClip)
  cubeOneMixer.time = 0
  cubeTwoMixer.time = 0
  setCollisionTimeouts()
  cubeOneAction.play()
  cubeTwoAction.play()
}

function setCollisionTimeouts() {
  for (const handler of collisionHandlers) clearTimeout(handler.timeout)
  collisionHandlers = [{ time: 0, timeout: null }]
  for (const collision of collisions.slice(0, -1)) {
    const deltaTime = collision.time - collisionHandlers[collisionHandlers.length - 1].time
    if (deltaTime >= 0.005) {
      const handler = {}
      handler.time = collision.time
      handler.timeout = setTimeout(() => {
        const cubeOneVelocity = Math.round(collision.cubeOneVelocity)
        const cubeTwoVelocity = Math.round(collision.cubeTwoVelocity)
        info.velocityOne.innerHTML = cubeOneVelocity > 0 ? '+' + cubeOneVelocity : cubeOneVelocity
        info.velocityTwo.innerHTML = cubeTwoVelocity > 0 ? '+' + cubeTwoVelocity : cubeTwoVelocity
        info.collisionCounter.innerHTML = collision.number
        if (simulation.soundVolume) bumpSound.play()
      }, handler.time * 1000)
      collisionHandlers.push(handler)
    }
  }
  const highlightHandler = {}
  highlightHandler.time = collisions[collisions.length - 2].time
  highlightHandler.timeout = setTimeout(() => {
    info.pi.className = 'highlight'
    info.collisionCounter.className = 'highlight'
  }, highlightHandler.time * 1000)
  collisionHandlers.push(highlightHandler)
}

// STATS

const stats = new Stats()
stats.domElement.style.position = 'absolute'
stats.domElement.style.top = 0
stats.domElement.style.left = 0

// 3D/2D HANDLING

function updatePerspective() {
  perspectiveCameraControls.enabled = !perspectiveCameraControls.enabled
  directionalLight.castShadow = !directionalLight.castShadow
}

if (navigator.userAgent.toLowerCase().includes('mobile')) {
  // launch in 2D on mobile devices
  simulation.threeD = false
  updatePerspective()
}

// PARAMETER CONTROLS

function addGUI() {
  const gui = new dat.GUI()

  const threeDCheckbox = gui.add(simulation, 'threeD')
  const soundVolumeSlider = gui.add(simulation, 'soundVolume', 0, 1, 0.1)
  simulation.soundVolumeSlider = soundVolumeSlider
  
  const massTwoExponentSlider = gui.add(simulation, 'massTwoExponent', 0, 6, 1)

  const cubeOneFolder = gui.addFolder('cube 1')
  const cubeOneInitialVelocitySlider = cubeOneFolder.add(simulation.cubeOne, 'initialVelocityValue', 0, 500, 25)
  const cubeOneInitialDistanceFromWallSlider = cubeOneFolder.add(simulation.cubeOne, 'initialDistanceFromWall', 10, 500, 10)
  const cubeOneSizeSlider = cubeOneFolder.add(simulation.cubeOne, 'size', 10, 500, 10)

  const cubeTwoFolder = gui.addFolder('cube 2')
  const cubeTwoInitialVelocitySlider = cubeTwoFolder.add(simulation.cubeTwo, 'initialVelocityValue', 25, 500, 25)
  const cubeTwoInitialDistanceFromCubeOneSlider = cubeTwoFolder.add(simulation.cubeTwo, 'initialDistanceFromCubeOne', 10, 500, 10)
  const cubeTwoSizeSlider = cubeTwoFolder.add(simulation.cubeTwo, 'size', 10, 500, 10)

  gui.add(simulation, 'playReset')
  
  threeDCheckbox.onChange(updatePerspective)
  soundVolumeSlider.onChange(updateVolume)
  cubeOneInitialVelocitySlider.onFinishChange(simulation.playResetWithRecalculation)
  cubeOneInitialDistanceFromWallSlider.onFinishChange(simulation.playResetWithRecalculation)
  cubeOneSizeSlider.onFinishChange(simulation.playResetWithRecalculation)
  cubeTwoInitialVelocitySlider.onFinishChange(simulation.playResetWithRecalculation)
  cubeTwoInitialDistanceFromCubeOneSlider.onFinishChange(simulation.playResetWithRecalculation)
  cubeTwoSizeSlider.onFinishChange(simulation.playResetWithRecalculation)
  massTwoExponentSlider.onFinishChange(simulation.playResetWithRecalculation)
}

// INITIALIZATION

if (THREE.WEBGL.isWebGLAvailable()) {
  document.body.appendChild(renderer.domElement)
  document.body.appendChild(stats.domElement)
  onresize = updateScreen
  addGUI()
  updateVolume()
  updateScreen()
  render()
  simulation.playReset()
  addEventListener('mousedown', () => {
    if (!simulation.clicked) {
      simulation.clicked = true
      const notice = document.getElementById('notice')
      if (notice) notice.remove()
      simulation.soundVolumeSlider.setValue(0.5)
      updateVolume()
    }
  })
} else {
  document.body.appendChild(THREE.WEBGL.getWebGLErrorMessage())
}

              
            
!
999px

Console