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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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="loading">
  <h2>Loading...</h2>
  <div class="spinner"></div>
</div>

              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700&display=swap');

:root {
  --button-spacing: 5px;
  --button-width: 32px;
}

* {
  -moz-user-select: none;  
  -ms-user-select: none;  
  -webkit-user-select: none;
  box-sizing: border-box;
  user-select: none;  
}

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

#loading {
  align-items: center;
  background-color: rgba(0, 0, 0, .8);
  color: #ccc;
  display: flex;
  flex-direction: column;
  font-family: Orbitron;
  height: 100%;
  justify-content: center;
  position: absolute;
  width: 100%;
  z-index: 2;
}

/**
 * Spinner
 */

//variables
$basic-dark-color: #cccccc; //color of the spinner
$border-width: 4px; //width of spinners border
$basic-spinner-dimensions: 125px; //width and height of spinner
$main-spinner-dimensions: $basic-spinner-dimensions - $border-width * 2; //width and height of bigger circle
$small-spinner-dimensions: $main-spinner-dimensions * 0.7; //width and height of smaller circle
.spinner {
  position: relative;
  width: $basic-spinner-dimensions;
  height: $basic-spinner-dimensions;

  &:before,
  &:after {
    content: "";
    display: block;
    position: absolute;
    border-width: 4px;
    border-style: solid;
    border-radius: 50%;
  }
  
  @keyframes scale-2 {
    0% {
      transform: scale(0);
      opacity: 0;
    }
    
    50% {
      transform: scale(0.7);
      opacity: 1;
    }
    
    100% {
      transform: scale(1);
      opacity: 0;
    }
  }
  
  &:before {
    width: $main-spinner-dimensions;
    height: $main-spinner-dimensions;
    border-color: $basic-dark-color;
    top: 0px;
    left: 0px;
    animation: scale-2 1s linear 0s infinite;
  }
  
  &:after {
    width: $main-spinner-dimensions;
    height: $main-spinner-dimensions;
    border-color: $basic-dark-color;
    top: 0;
    left: 0;
    opacity: 0;
    animation: scale-2 1s linear 0.5s infinite;
  }
}

              
            
!

JS

              
                console.clear()

const {
  devicePixelRatio,
  innerHeight: viewportHeight,
  innerWidth: viewportWidth
} = window

class Pen {
  #controls
  #orbital
  #player
  #prevTimestamp
  #renderer
  #scene

  static timeDilation = 0.4
  constructor () {
    this.#scene = new THREE.Scene()
    this.#renderer = new THREE.WebGLRenderer({ antialias: true })
    this.#renderer.shadowMap.enabled = true

    this.#addPlayer()
    this.#addGround()
    this.#addLights()

    document.body.appendChild(this.#renderer.domElement)

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

  #addPlayer () {
    this.#controls = {
      position: new TouchInput({ left: true }),
      rotation: new TouchInput({ right: true })
    }
    this.#player = new Player({
      animationNames: ['idle', 'walk', 'run'],
      modelName: 'root',
      onLoad: () => document.querySelector('#loading').style.display = 'none',
      path: 'https://assets.codepen.io/829639/'
    })
    this.#scene.add(this.#player)

    this.#orbital = new OrbitalCamera(
      60,
      viewportWidth / viewportHeight,
      1,
      1000
    )
    this.#player.add(this.#orbital)
  }

  #addGround () {
    const grid = new THREE.InfiniteGridHelper(10, 100)
    grid.receiveShadow = true
    this.#scene.add(grid)

    const axesHelper = new THREE.AxesHelper(15)
    this.#scene.add(axesHelper)
  }

  #addLights () {
    const directional = new THREE.DirectionalLight(0xffffff, 2)
    directional.position.set(50, 50, 50)
    directional.target.position.set(0, 0, 0)
    directional.castShadow = true
    directional.shadow.bias = -0.001
    directional.shadow.mapSize.width = 4096
    directional.shadow.mapSize.height = 4096
    directional.shadow.camera.near = 0.1
    directional.shadow.camera.far = 500.0
    directional.shadow.camera.near = 0.5
    directional.shadow.camera.far = 500.0
    directional.shadow.camera.left = 50
    directional.shadow.camera.right = -50
    directional.shadow.camera.top = 50
    directional.shadow.camera.bottom = -50
    this.#scene.add(directional)

    const ambient = new THREE.AmbientLight(0xffffff, .5)
    this.#scene.add(ambient)
  }

  #update = elapsedTime => {
    this.#renderer.setSize(window.innerWidth, window.innerHeight)

    const easeIn = 91
    let { x: yRotation, y: xRotation } = this.#controls.rotation
    xRotation = Math.pow(xRotation, easeIn)
    
    const cameraRotation = new THREE.Euler(xRotation, yRotation, 0)
    this.#orbital.update(elapsedTime, cameraRotation)

    const { x: xPos, y: zPos } = this.#controls.position
    const playerPosition = new THREE.Vector3(xPos, 0, zPos)
    playerPosition.multiplyScalar(Pen.timeDilation)
    playerPosition.applyEuler(this.#orbital.rotation)

    this.#player.update(elapsedTime, playerPosition)
  }

  #render = timestamp => {
    if (this.#prevTimestamp === undefined) this.#prevTimestamp = timestamp

    const elapsedTime = (timestamp - this.#prevTimestamp) / 1000
    this.#renderer.render(this.#scene, this.#orbital.camera)
    this.#update(elapsedTime)
    this.#prevTimestamp = timestamp

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

class OrbitalCamera extends THREE.Object3D {
  #originalCameraAngle
  constructor (fov, aspect, near, far) {
    super()

    this.camera = new THREE.PerspectiveCamera(fov, aspect, near, far)
    this.camera.position.set(2, 25, 35)
    this.camera.lookAt(0, 20, 0)
    this.add(this.camera)
    this.#originalCameraAngle = this.camera.rotation.x

  }

  update (elapsedTime, rotation) {
    this.camera.aspect = window.innerWidth / window.innerHeight
    this.camera.updateProjectionMatrix()

    if (rotation instanceof THREE.Euler) {
      const groupY = this.rotation.y + rotation.y * -elapsedTime
      this.rotation.set(0, groupY, 0)
                  
      const newCamPos = this.camera.position.clone()
      newCamPos.setY(25 - (rotation.x * 11))
      this.camera.position.lerp(newCamPos, .1)
      
      const newCamQuat = this.camera.quaternion.clone()
      newCamQuat.setFromAxisAngle(
        new THREE.Vector3(1, 0, 0),
        this.#originalCameraAngle + rotation.x * Pen.timeDilation
      )
      this.camera.quaternion.slerp(newCamQuat, .1)
    }

    this.camera.aspect = window.innerWidth / window.innerHeight
    this.camera.updateProjectionMatrix()
  }
}

class Player extends THREE.Group {
  #action
  #actionList = {}
  #areModelsLoaded = false
  #mixer
  #model

  constructor (props) {
    super()

    const { animationNames, modelName, onLoad, path } = props
    const loader = new THREE.FBXLoader()
    loader.setPath(path)
    loader.load(
      `${modelName}.fbx`,
      model => {
        /**
         * Resize the model I happened to use. Not a required.
         */
        model.scale.setScalar(0.1)

        /**
         * Change the colors of some of the materials in the model I happened to use. Not a required.
         */
        model.traverse(mesh => {
          mesh.castShadow = true
          if (mesh.material?.name === 'asdf1:Beta_HighLimbsGeoSG2') {
            mesh.material.color.setHex(0x333333)
            mesh.metalicness = 1
            mesh.roughness = 0
          } else if (mesh.material?.name === 'Beta_Joints_MAT') {
            mesh.material.color.setRGB(
              (Math.floor(Math.random() * 80) + 20) / 100,
              (Math.floor(Math.random() * 80) + 20) / 100,
              (Math.floor(Math.random() * 80) + 20) / 100
            )
          }
        })

        model.position.set(0, 0, 0)
        model.setRotationFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI)
        this.#model = model
        this.add(model)

        this.#mixer = new THREE.AnimationMixer(this.#model)

        const loadingManager = new THREE.LoadingManager()
        const loader = new THREE.FBXLoader(loadingManager)
        loader.setPath(path)
        loadingManager.onLoad = () => {
          this.#areModelsLoaded = true
          this.#setAction('idle')
          if (typeof onLoad === 'function') onLoad()
        }

        animationNames.forEach(name => {
          loader.load(`${name}.fbx`, model => {
            const clip = model.animations[0]
            const action = this.#mixer.clipAction(clip)
            action.name = name

            this.#actionList[name] = action
          })
        })
      },
      null,
      e => console.log(e)
    )
  }

  update = (elapsedTime, movement) => {
    if (!this.#action) return
    this.#animate(elapsedTime, movement)
    this.#move(elapsedTime, movement)
  }

  #animate = (elapsedTime, movement) => {
    const { x, z } = movement

    const speed = Math.min(Math.abs(x) + Math.abs(z), 1)

    let action = 'idle'

    if (speed === 0) action = 'idle'
    else if (speed < 0.3) action = 'walk'
    else action = 'run'

    this.#setAction(action)
    this.#mixer.update(elapsedTime)
  }

  #move = (elapsedTime, movement) => {
    if (!movement instanceof THREE.Vector3) return
    if (movement.x === 0 && movement.z === 0) return

    const nextPosition = this.position.clone()
    nextPosition.add(movement)

    const angle =
      Math.PI +
      Math.atan2(
        this.position.x - nextPosition.x,
        this.position.z - nextPosition.z
      )

    this.position.copy(nextPosition)

    if (this.#model)
      this.#model.setRotationFromAxisAngle(new THREE.Vector3(0, 1, 0), angle)
  }

  #setAction (name) {
    const prevAction = this.#action
    if (prevAction?.name === name) return

    this.#action = this.#actionList[name]

    if (prevAction) {
      this.#action.time = 0.1
      this.#action.enabled = true
      this.#action.setEffectiveTimeScale(Pen.timeDilation)
      this.#action.setEffectiveWeight(1.0)
      this.#action.crossFadeFrom(prevAction, 0.5, true)
    }

    this.#action.play()
  }
}

class TouchInput extends THREE.Vector3 {
  constructor (options) {
    super()
    
    const circle = document.createElement('div')
    if (options.left !== undefined) {
      circle.style.cssText = `
        background: rgba(126, 126, 126, 0.5);
        border: #444 solid medium;
        border-radius: 50%;
        bottom: 35px;
        height: 80px;
        left: 35px;
        position: absolute;
        width: 80px;
        z-index:  1;
      `
    } else if (options.right !== undefined) {
      circle.style.cssText = `
        background: rgba(126, 126, 126, 0.5);
        border: #444 solid medium;
        border-radius: 50%;
        bottom: 35px;
        height: 80px;
        position: absolute;
        right: 35px;
        width: 80px;
        z-index:  1;      
      `
    } else {
      circle.style.cssText = `
        background: rgba(126, 126, 126, 0.5);
        border: #444 solid medium;
        border-radius: 50%;
        bottom: 35px;
        height: 80px;
        left: 50%;
        position: absolute;
        transform: translateX(-50%);
        width: 80px;
        z-index:  1;
      `
    }
    const thumb = document.createElement('div')
    const threshold = document.createElement('div')
    thumb.style.cssText = `
      background-color: #fff;
      border-radius: 50%;
      height: 40px;
      left: 17px;
      position: absolute;
      top: 17px;
      width: 40px;
      z-index: 2;
    `
    threshold.style.cssText = `
      background-color: rgba(255, 255, 255, .1);
      border-radius: 50%;
      height: 120px;
      left: -40px;
      margin: auto;
      position: absolute;
      top: -40px;
      width: 120px;
      z-index: 1
    `
    thumb.appendChild(threshold)
    circle.appendChild(thumb)
    document.body.appendChild(circle)
    this.domBg = circle
    this.domElement = thumb
    this.maxRadius = options.maxRadius || 40
    this.maxRadiusSquared = this.maxRadius * this.maxRadius
    this.origin = {
      left: this.domElement.offsetLeft,
      top: this.domElement.offsetTop
    }
    this.isMouseDown = false

    if ('ontouchstart' in window) {
      this.domElement.addEventListener('touchstart', this.tap)
      this.domElement.addEventListener('touchmove', this.move)
      this.domElement.addEventListener('touchend', this.up)
    } else {
      this.domElement.addEventListener('mousedown', this.tap)
      this.domElement.addEventListener('mousemove', this.move)
      this.domElement.addEventListener('mouseup', this.up)
      this.domElement.addEventListener('mouseout', this.up)
    }
    
    this.up(new Event(''))
  }

  set visible (mode) {
    const setting = mode ? 'block' : 'none'
    this.domElement.style.display = setting
    this.domBg.style.display = setting
  }

  getMousePosition (event) {
    let clientX = event.targetTouches
      ? event.targetTouches[0].pageX
      : event.clientX
    let clientY = event.targetTouches
      ? event.targetTouches[0].pageY
      : event.clientY
    return { x: clientX, y: clientY }
  }

  tap = e => {
    const event = e || window.event
    event.preventDefault()
    
    this.isMouseDown = true

    this.offset = this.getMousePosition(event)
  }

  move = e => {
    if (!this.isMouseDown) return

    const event = e || window.event
    event.preventDefault()

    const mouse = this.getMousePosition(event)
    let left = mouse.x - this.offset.x
    let top = mouse.y - this.offset.y

    const sqMag = left * left + top * top
    if (sqMag > this.maxRadiusSquared) {
      const magnitude = Math.sqrt(sqMag)
      left /= magnitude
      top /= magnitude
      left *= this.maxRadius
      top *= this.maxRadius
    }

    this.domElement.style.top = `${top + this.domElement.clientHeight / 2}px`
    this.domElement.style.left = `${left + this.domElement.clientWidth / 2}px`

    const x =
      (left - this.origin.left + this.domElement.clientWidth / 2) /
      this.maxRadius
    const y =
      (top - this.origin.top + this.domElement.clientHeight / 2) /
      this.maxRadius

    this.set(x, y, 0)
    this.normalize()
  }

  up = e => {
    const event = e || window.event
    event.preventDefault()

    this.isMouseDown = false

    this.domElement.style.top = `${this.origin.top}px`
    this.domElement.style.left = `${this.origin.left}px`
    this.set(0, 0, 0)
  }
}

new Pen()

              
            
!
999px

Console