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;
  }
}

/* Joysticks */
.joystick {
  background: rgba(100, 100, 100, 0.5);
  border: 3px solid rgb(100, 100, 100);
  border-radius: 50%;
  height: 80px;
  position: absolute;
  width: 80px;
  z-index:  1;

  &.left {
    bottom: 35px;
    left: 35px;
  }

  &.right {
    bottom: 35px;
    right: 35px;
  }

  &.center {
    bottom: 35px;
    left: 50%;
    transform: translateX(-50%);
  }

  .thumb {
    background-color: #fff;
    border-radius: 50%;
    height: 40px;
    left: 17px;
    position: absolute;
    top: 17px;
    width: 40px;
    z-index: 2;
  }

  .threshold {
    background-color: rgba(255, 255, 255, .1);
    border-radius: 50%;
    height: 150px;
    left: -55px;
    margin: auto;
    position: absolute;
    top: -55px;
    width: 150px;
    z-index: 1
  }
}
              
            
!

JS

              
                console.clear()

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

class Scene extends THREE.Scene {
  #building
  #controls
  #orbital
  #player
  #prevTimestamp
  #renderer
  #scene

  static width = 30
  static height = 30
  static timeDilation = 0.4

  constructor () {
    super()

    this.#renderer = new THREE.WebGLRenderer({ antialias: true })
    this.#renderer.shadowMap.enabled = true

    this.#addPlayer()
    this.#addBuilding()

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

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

  #addPlayer () {
    // Create the playable character
    this.#player = new Player({
      animationNames: ['idle', 'walk', 'run'],
      modelName: 'root',
      onLoad: () => (document.querySelector('#loading').style.display = 'none'),
      path: 'https://assets.codepen.io/829639/'
    })
    this.add(this.#player)

    // Create the player/camera controls
    this.#controls = {
      position: new TouchInput(TouchInput.POSITION_LEFT),
      rotation: new TouchInput(TouchInput.POSITION_RIGHT)
    }

    // Create the orbital camera, and attach it to the player
    const aspect = viewportWidth / viewportHeight
    this.#orbital = new OrbitalCamera(60, aspect, 1, 1000)
    this.#player.add(this.#orbital)
  }

  #addBuilding () {
    this.#building = new Building()
    this.add(this.#building)
  }

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

    // Update orbital camera rotation based on the controls
    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)

    // Update player position and rotation based on the controls
    const { x: xPos, y: zPos } = this.#controls.position
    const playerPosition = new THREE.Vector3(xPos, 0, zPos)
    playerPosition.multiplyScalar(Scene.timeDilation)
    playerPosition.applyEuler(this.#orbital.rotation)
    this.#player.update(elapsedTime, playerPosition)

    // Update wall viewability based on whether they're blocking the view
    const raycaster = new THREE.Raycaster()
    const cameraWorldPosition = new THREE.Vector3()
      this.#orbital.camera.getWorldPosition(cameraWorldPosition)
    const targetWorldPosition = new THREE.Vector3()
      this.#player.getWorldPosition(targetWorldPosition)
    const dir = cameraWorldPosition.clone().sub(targetWorldPosition).normalize()
    const maxDistance = cameraWorldPosition.distanceTo(targetWorldPosition)
    raycaster.set(targetWorldPosition, dir)
    this.#building.update(raycaster, maxDistance)
  }

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

    const elapsedTime = (timestamp - this.#prevTimestamp) / 1000
    this.#update(elapsedTime)
    this.#prevTimestamp = timestamp

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

class Building extends THREE.Group {
  #sides = []

  constructor () {
    super()

    this.#addLights()
    this.#addStructure()
  }

  #addSide (side) {
    this.#sides.push(side)
    this.add(side)
  }

  #addStructure () {
    const halfWidth = Scene.width / 2
    const halfHeight = Scene.height / 2
    const halfTurn = Math.PI / 2
    const floorGeometry = new THREE.BoxGeometry(Scene.width, 0.1, Scene.width)
    const floorMaterial = new THREE.MeshStandardMaterial({
      color: 0xffffff,
      metalness: .2,
      roughness: 0
    })
    const floor = new THREE.Mesh(floorGeometry, floorMaterial)
    floor.receiveShadow = true
    floor.position.set(0, 0, 0)
    floor.name = 'floor'
    floor.userData.normal = new THREE.Vector3(0, 0, -1)
    this.#addSide(floor)

    const ceiling = floor.clone()
    ceiling.position.set(0, Scene.height, 0)
    ceiling.name = 'ceiling'
    ceiling.userData.normal = new THREE.Vector3(0, 0, -1)
    this.#addSide(ceiling)

    const northWall = this.#makeWall('north')
    northWall.position.set(0, halfHeight, -halfWidth)
    const southWall = this.#makeWall('south')
    southWall.position.set(0, halfHeight, halfWidth)
    const westWall = this.#makeWall('west')
    westWall.rotateY(halfTurn)
    westWall.position.set(-halfWidth, halfHeight, 0)
    const eastWall = this.#makeWall('east')
    eastWall.rotateY(-halfTurn)
    eastWall.position.set(halfWidth, halfHeight, 0)
  }

  #addLights () {
    const lastLight = Scene.width - 20
    const halfWidth = Scene.width / 2

    const ambient = new THREE.AmbientLight(0xffffff, .3)
    this.add(ambient)

    for (let x = 0; x <= Scene.width; x += 100) {
      for (let z = 0; z <= Scene.width; z += 100) {
        const position = new THREE.Vector3(x - halfWidth, 20, z - halfWidth)
        const target = new THREE.Vector3(x - halfWidth, 0, z - halfWidth)
        this.#makeLight(position, target)
      }
    }
  }

  #makeLight (position, target) {
    const light = new THREE.SpotLight(0xffffff, 1)
    light.position.copy(position)
    light.target.position.copy(target)
    light.castShadow = true
    this.add(light)
  }

  #makeWall (name, color = 0xffffff) {
    const wallGeometry = new THREE.BoxGeometry(Scene.width, Scene.height, 0.1)
    const wallMaterial = new THREE.MeshStandardMaterial({
      color,
      metalness: 0,
      roughness: 0,
      transparent: false,
      opacity: .5,
    })
    const wall = new THREE.Mesh(wallGeometry, wallMaterial)
    wall.receiveShadow = true
    wall.name = name
    this.#addSide(wall)

    return wall
  }

  update = (raycaster, maxDistance) => {
    try {
      const test = this.#sides[2]
      const activeSides = raycaster.intersectObjects(this.#sides)

      this.#sides.forEach(side => {
        const activeSide = activeSides.find(s => s.object.name === side.name)
        const isBlockingView = !!activeSide && activeSide.distance < maxDistance
        // side.material.opacity = isBlockingView ? 0.2 : 1
        side.material.wireframe = isBlockingView

      })
    } catch (e) {
      console.error('OOPS:', e)
    }
  }
}

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, 20, 30)
    this.camera.lookAt(0, 5, 0)
    this.add(this.camera)
    this.#originalCameraAngle = this.camera.rotation.x
  }

  update (elapsedTime, rotation) {
    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(20 - rotation.x * 11)
      this.camera.position.lerp(newCamPos, 0.1)

      const newCamQuat = this.camera.quaternion.clone()
      newCamQuat.setFromAxisAngle(
        new THREE.Vector3(1, 0, 0),
        this.#originalCameraAngle + rotation.x * Scene.timeDilation
      )
      this.camera.quaternion.slerp(newCamQuat, 0.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.04)

        /**
         * 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 oldPosition = this.position.clone()
    const halfWidth = Scene.width / 2 - 1.1
    const nextPosition = this.position.clone()
    nextPosition.add(movement)

    if (nextPosition.x < -halfWidth) nextPosition.x = -halfWidth
    if (nextPosition.z < -halfWidth) nextPosition.z = -halfWidth
    if (nextPosition.x > halfWidth) nextPosition.x = halfWidth
    if (nextPosition.z > halfWidth) nextPosition.z = halfWidth
    this.position.copy(nextPosition)


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

    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(Scene.timeDilation)
      this.#action.setEffectiveWeight(1.0)
      this.#action.crossFadeFrom(prevAction, 0.5, true)
    }

    this.#action.play()
  }
}

class TouchInput extends THREE.Vector3 {
  static POSITION_CENTER = 'center'
  static POSITION_LEFT = 'left'
  static POSITION_RIGHT = 'right'

  constructor (position = TouchInput.POSITION_CENTER) {
    super()

    const joystick = document.createElement('div')
    const thumb = document.createElement('div')
    const threshold = document.createElement('div')
    thumb.appendChild(threshold)
    joystick.appendChild(thumb)
    
    joystick.className = 'joystick'
    if (position === TouchInput.POSITION_LEFT) {
      joystick.className = `${joystick.className} left`
    } else if (position === TouchInput.POSITION_RIGHT) {
      joystick.className = `${joystick.className} right`
    } else {
      joystick.className = `${joystick.className} center`
    }
    thumb.className = 'thumb'
    threshold.className = 'threshold'

    document.body.appendChild(joystick)
    this.domElement = thumb
    this.maxRadius = 55
    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(''))
  }

  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 Scene()

              
            
!
999px

Console