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

              
                <!-- <footer class="footer v-dark">
 Made with ☕ by <a class="footer-anchor" target="_blank" href="https://twitter.com/zadvorsky">Szenia</a>
</footer> -->

<div id="three-container"></div>
<div id="ui-container"></div>
              
            
!

CSS

              
                @import url("https://fonts.googleapis.com/css?family=VT323");

$black: #343436;
$white: #fff;
$yellow: #fcd000;

*,
*:before,
*:after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

html,
body {
 width: 100%;
 height: 100%;
 overflow: hidden;
 font-family: "VT323", monospace;
}

.footer {
 position: fixed;
 right: 0;
 bottom: 0;
 left: 0;
 padding: 10px 10px;
 text-align: right;
 font-family: "Roboto", sans-serif;
 font-size: 12px;

 &.v-dark {
  background-color: $black;
  color: $white;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
 }
 &.v-light {
  background-color: $white;
  color: $black;
 }
}

.footer-anchor {
 display: inline-block;
 margin-left: 5px;
 padding: 2px 4px;
 color: $black;
 text-decoration: none;
 background-color: $yellow;
 border-radius: 4px;
 opacity: 1;
 transition: opacity 0.2s;

 &:hover {
  opacity: 0.6;
 }
}

#three-container {
 position: absolute;
 left: 0;
 top: 0;
}

#ui-container {
 position: absolute;
 left: 0;
 top: 0;
 width: 100%;
 height: 100%;
}

.flex-container {
 display: flex;
 height: 100%;
 flex-direction: column;
 align-items: center;
 justify-content: center;
}

.button {
 position: relative;
 font-size: 80px;
 padding: 12px;
 background: black;
 color: #e9f259;
 cursor: pointer;
}
.button:hover {
 box-shadow: #d46ce7 10px 10px 0 0;
}

.title {
 font-size: 80px;
 line-height: 1;
 margin-bottom: 40px;
}

.score {
 font-size: 40px;
 line-height: 1;
 margin-bottom: 56px;
}

.score-display {
 position: absolute;
 bottom: 0;
 left: 0;
 width: 100%;
 /*color: #89aee1;*/
 color: black;
 font-size: 120px;
 text-align: center;
}

.life-display {
 position: absolute;
 left: 12px;
 top: 12px;
}
.live-item {
 display: inline-block;
 width: 64px;
 height: 64px;
 margin-right: 12px;
 background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/304639/heart.png");
 background-size: contain;
}
.live-item.depleted {
 opacity: 0.25;
}

              
            
!

JS

              
                const GLOBAL = {
  rootURL: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/304639/',

  colors: {
    yellow: '#e9f259',
    pink: '#d46ce7'
  },

  sounds: {
    bgm: 'szenia_codepen_tune2.mp3',
    score: 'smw_coin.wav',
    hit: 'smw_thud.wav'
  },

  textures: {
    surfer: 'internet_boy.png',

    good: [
      'apple.png',
      'clippy.png',
      'mtv.png',
      'netscape.png',
      'pokeball.png',
      'wordart.png'
    ],

    bad: [
      'blinky.png',
      'goomba.png'
    ]
  },
  anisotropy: 1,

  gameSpeed: 1.0
};

// utils

const utils = {
  getRandom(array) {
    return array[(Math.random() * array.length) | 0];
  }
};

// Wave

class Wave extends THREE.Mesh {
  constructor(params) {
    const textureSize = 64;

    const textureCanvas = document.createElement('canvas');
    textureCanvas.width = textureCanvas.height = textureSize;

    const textureCtx = textureCanvas.getContext('2d');
    textureCtx.fillStyle = GLOBAL.colors.yellow;
    textureCtx.fillRect(0, 0, textureSize, textureSize);
    textureCtx.lineWidth = 8;
    textureCtx.strokeStyle = GLOBAL.colors.pink;
    textureCtx.strokeRect(0, 0, textureSize, textureSize);

    const texture = new THREE.CanvasTexture(textureCanvas);
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.repeat.set(50, 50);
    texture.anisotropy = GLOBAL.anisotropy;

    const model = new THREE.PlaneGeometry(100, 100, 100, 100);
    model.rotateX(-Math.PI * 0.5);

    const geometry = new BAS.ModelBufferGeometry(model);
    geometry.bufferUVs();

    const material = new BAS.BasicAnimationMaterial({
      uniformValues: {
        map: texture,
        offsetRepeat: new THREE.Vector4(0, 0, texture.repeat.x, texture.repeat.y)
      },
      uniforms: {
        xCurve: { value: params.xCurvePoints },
        zCurve: { value: params.zCurvePoints },
      },
      vertexParameters: `
        uniform vec3 xCurve[5];
        uniform vec3 zCurve[4];
      `,
      vertexFunctions: [
        BAS.ShaderChunk.catmull_rom_spline, `
        vec3 sampleOffsetX(float p) {
          float pt = p * 4.0;
          ivec4 indices = getCatmullRomSplineIndices(4.0, pt);
      
          vec3 p0 = xCurve[indices[0]];
          vec3 p1 = xCurve[indices[1]];
          vec3 p2 = xCurve[indices[2]];
          vec3 p3 = xCurve[indices[3]];
      
          return catmullRomSpline(p0, p1, p2, p3, fract(pt));
        }
        `, `
        vec3 sampleOffsetZ(float p) {
          float pt = p * 3.0;
          ivec4 indices = getCatmullRomSplineIndices(3.0, pt);
      
          vec3 p0 = zCurve[indices[0]];
          vec3 p1 = zCurve[indices[1]];
          vec3 p2 = zCurve[indices[2]];
          vec3 p3 = zCurve[indices[3]];
      
          return catmullRomSpline(p0, p1, p2, p3, fract(pt));
        }
      `
      ],
      vertexPosition: `
        vec3 xOffset = sampleOffsetX((transformed.x + 50.0) * 0.01);
        transformed.x = xOffset.x;
        transformed.yz += xOffset.yz;
        
        vec3 zOffset = sampleOffsetZ((transformed.z + 50.0) * 0.01);
        transformed.z = zOffset.z;
        transformed.xy += zOffset.xy;
      `,
    });

    super(geometry, material);
  }

  update() {
    this.material.uniforms.offsetRepeat.value.y -= 0.15 * GLOBAL.gameSpeed;
  }
}

// Surfer

class Surfer extends THREE.Mesh {

  static radius = 16;
  static xRange = 40;
  static maxVelocity = 12;
  static defaultAccelerationDecay = 0.98;
  static edgeAccelerationDecay = 0.75;
  static acceleration = 0.075;
  static yAnchor = 20;
  static zAnchor = 4;

  velocity = 0;
  idleTime = 0;
  isInvincible = false;
  isDead = false;

  constructor() {
    const geometry = new THREE.PlaneGeometry(Surfer.radius * 2, Surfer.radius * 2);
    geometry.translate(0, Surfer.radius * 0.75, 0);

    const material = new THREE.MeshBasicMaterial({
      map: new THREE.TextureLoader().load(GLOBAL.rootURL + GLOBAL.textures.surfer),
      transparent: true,
      side: THREE.DoubleSide
    });

    super(geometry, material);

    this.hitbox = new THREE.Box3();
  }

  reset() {
    this.velocity = 0;
    this.idleTime = 0;
    this.isInvincible = false;
    this.isDead = false;
    this.position.set(0, Surfer.yAnchor, Surfer.zAnchor);
    this.rotation.set(0, 0, 0);
    this.scale.set(1, 1, 1);
  }

  update(keys) {
    if (this.isDead === true) return;

    // update idle wobble
    this.idleTime += 1/30;
    this.position.y = Surfer.yAnchor + Math.sin(this.idleTime * 4) * 0.5;

    // decay velocity
    if (this.position.x === -Surfer.xRange || this.position.x === Surfer.xRange) {
      this.velocity *= Surfer.edgeAccelerationDecay;
    }
    else {
      this.velocity *= Surfer.defaultAccelerationDecay;
    }

    // apply keys
    if (keys.left) {
      this.velocity = Math.max(-Surfer.maxVelocity, this.velocity - Surfer.acceleration * GLOBAL.gameSpeed);
    }

    if (keys.right) {
      this.velocity = Math.min(Surfer.maxVelocity, this.velocity + Surfer.acceleration * GLOBAL.gameSpeed);
    }

    this.position.x = THREE.Math.clamp(this.position.x + this.velocity, -Surfer.xRange, Surfer.xRange);

    // rotate based on velocity
    this.rotation.z = this.velocity * 0.2;

    this.hitbox.setFromObject(this);
  }

  score() {
    return TweenMax.to(this.scale, 0.25, {
      x: 0.8,
      y: 1.2,
      ease: Power3.easeIn,
      repeat: 1,
      yoyo: true
    })
  }

  hit() {
    this.isInvincible = true;

    let frame = 0;

    return TweenMax.to(this.rotation, 1, {y: Math.PI * 2, ease: Back.easeOut,
      onUpdate: () => {
        ++frame % 4 === 0 && (this.material.visible = !this.material.visible);
      },
      onComplete: () => {
        this.material.visible = true;
        this.isInvincible = false;
        this.rotation.y = 0;
      }
    });
  }

  kill() {
    this.isDead = true;

    let frame = 0;

    const tl = new TimelineMax({onUpdate: () => {
      ++frame % 4 === 0 && (this.material.visible = !this.material.visible);
    }});

    tl.to(this.rotation, 1, {z: Math.PI, ease: Back.easeIn}, 0);
    tl.to(this.position, 0.5, {y: -10, ease: Power2.easeOut});

    return tl;
  }
}

// Items

class Items extends THREE.Group {

  itemPool = [];
  itemCount = 0;

  constructor(params) {
    super();

    this.xSpline = new THREE.CatmullRomCurve3(params.xCurvePoints);
    this.zSpline = new THREE.CatmullRomCurve3(params.zCurvePoints);
    this.xSpline.type = 'catmullrom';
    this.zSpline.type = 'catmullrom';

    this.collisionHandler = params.collisionHandler;

    this.spawn();
  }

  reset() {
    this.itemCount = 0;
  }

  spawn() {
    const item = this.itemPool.shift() || new Item();

    item.reset(Math.random() > 0.25 ? 'good' : 'bad');
    item.position.x = THREE.Math.randFloatSpread(Surfer.xRange * 2);

    this.add(item);

    if (++this.itemCount % 4 === 0) {
      GLOBAL.gameSpeed *= 1.1;

      console.log('GAME SPEED UP!', GLOBAL.gameSpeed);
    }
  }

  pool(item) {
    this.remove(item);
    this.itemPool.push(item);
  }

  update(surfer) {
    if (this.children.length === 0) {
      this.spawn();
    }

    for (let i = this.children.length -1; i >= 0; i--) {
      const item = this.children[i];

      item.update(this.zSpline);

      if (item.isComplete()) {
        this.pool(item);
      }
      else if (surfer.isDead === false && this.checkCollision(item, surfer)) {
        if (!(surfer.isInvincible && item.value < 0)) {
          this.collisionHandler(item.value);
          this.pool(item);
        }
      }
    }
  }

  checkCollision(item, surfer) {
    item.updateHitbox();

    return item.hitbox.intersectsBox(surfer.hitbox);
  }

  clear() {
    for (let i = this.children.length - 1; i >= 0; i--) {
      this.pool(this.children[i]);
    }
  }
}

// Item

class Item extends THREE.Mesh {

  static yAnchor = 20;
  
  enabled = false;
  pathProgress = 0;
  speed = 1/240;

  prevPosition = new THREE.Vector3();
  tempVector = new THREE.Vector3();

  constructor() {
    const size = 10;
    const geometry = new THREE.PlaneBufferGeometry(size, size);
    const material = new THREE.MeshBasicMaterial({
      map: new THREE.Texture(),
      transparent: true,
      // depthWrite: true,
      // depthTest: false,
    });

    super(geometry, material);

    this.size = size;
    this.hitbox = new THREE.Box3();

    this.textureLoader = new THREE.TextureLoader();
  }

  loadTexture(name) {
    this.textureLoader.load(GLOBAL.rootURL + name, (t) => {
      this.material.map = t;
      this.material.visible = true;
      this.enabled = true;
    });
  }

  reset(type) {
    this.material.visible = false;
    this.enabled = false;
    
    switch(type) {
      case 'good':
        this.value = 100;
        this.loadTexture(utils.getRandom(GLOBAL.textures.good));
        break;
      case 'bad':
        this.value = -1;
        this.loadTexture(utils.getRandom(GLOBAL.textures.bad));
        break;
    }

    this.pathProgress = 0;
  }

  update(spline) {
    if (this.enabled) {
      this.pathProgress = Math.min(1.0, this.pathProgress + this.speed * GLOBAL.gameSpeed);
    }
    else {
      this.pathProgress = 0; 
    }

    const pz = spline.getPointAt(1 - this.pathProgress, this.tempVector);

    this.prevPosition.copy(this.position);
    this.position.y = pz.y + Item.yAnchor;
    this.position.z = pz.z;
  }

  updateHitbox() {
    this.hitbox.min.set(
      this.position.x - this.size * 0.5,
      this.position.y - this.size * 0.5,
      this.position.z
    );
    this.hitbox.max.set(
      this.prevPosition.x + this.size * 0.5,
      this.prevPosition.y + this.size * 0.5,
      this.prevPosition.z
    );
  }

  isComplete() {
    return this.pathProgress >= 1;
  }
}

// Start state

class StartState {

  constructor(params) {
    this.webgl = new THREE.Group();
    this.html = document.createElement('div');
    this.html.className = 'flex-container';

    this.gameStartHandler = params.gameStartHandler;
  }

  enter() {
    this.html.innerHTML = `
      <div class="title">SURF THE WEB!</div>
      <div class="button">PLAY</div>
    `;

    this.button = this.html.querySelector('.button');
    this.button.addEventListener('click', this.gameStartHandler);
  }

  update() {}

  leave() {
    this.button.removeEventListener('click', this.gameStartHandler);
  }
}

// Play state

class PlayState {

  xCurvePoints = [
    new THREE.Vector3(-120, -8, 0),
    new THREE.Vector3(-25, 4, 0),
    new THREE.Vector3(0, -5, 0),
    new THREE.Vector3(25, 4, 0),
    new THREE.Vector3(120, -8, 0),
  ];

  zCurvePoints = [
    new THREE.Vector3(0, 100, -50),
    new THREE.Vector3(0, 20, -5),
    new THREE.Vector3(0, 10, 25),
    new THREE.Vector3(0, 0, 50),
  ];

  keys = {
    left: false,
    right: false
  };

  score = 0;
  lives = 3;

  constructor(params) {
    this.webgl = new THREE.Group();
    this.html = document.createElement('div');
    this.html.className = 'flex-container';

    this.surfer = new Surfer();
    this.webgl.add(this.surfer);

    this.wave = new Wave({
      xCurvePoints: this.xCurvePoints,
      zCurvePoints: this.zCurvePoints
    });
    this.webgl.add(this.wave);

    this.items = new Items({
      xCurvePoints: this.xCurvePoints,
      zCurvePoints: this.zCurvePoints,
      collisionHandler: this.collisionHandler
    });
    this.webgl.add(this.items);

    this.gameOverHandler = params.gameOverHandler;
    this.camera = params.camera;

    this.camera.position.set(0, Surfer.yAnchor, 60);
    this.cameraTarget = new THREE.Vector3(0, Surfer.yAnchor, 0);

    // setup audio
    this.bgm = new Howl({
      src: GLOBAL.rootURL + GLOBAL.sounds.bgm,
      loop: true,
      volume: 0.5,
    });
    this.hitSound = new Howl({
      src: GLOBAL.rootURL + GLOBAL.sounds.hit
    });
    this.scoreSound = new Howl({
      src: GLOBAL.rootURL + GLOBAL.sounds.score
    });

    this.filterNode = Howler.ctx.createBiquadFilter();
    this.filterNode.type = 'lowpass';
    this.filterNode.frequency.value = 22050;

    Howler.masterGain.disconnect();
    Howler.masterGain.connect(this.filterNode);
    this.filterNode.connect(Howler.ctx.destination);
  }

  reset() {
    this.keys.left = false;
    this.keys.right = false;
    this.surfer.reset();
    this.items.reset();
    this.score = 0;
    this.lives = 3;

    GLOBAL.gameSpeed = 1.0;
  }

  enter() {
    this.reset();
    this.updateUI();

    window.addEventListener('keyup', this.handleKeyUp);
    window.addEventListener('keydown', this.handleKeyDown);

    this.bgm.play();
    this.filterNode.frequency.value = 10000;
  }

  update() {
    this.surfer.update(this.keys);

    this.cameraTarget.x = this.surfer.position.x * 0.025;
    this.camera.lookAt(this.cameraTarget);

    this.xCurvePoints[1].x = this.surfer.position.x - Surfer.radius * 2;
    this.xCurvePoints[2].x = this.surfer.position.x;
    this.xCurvePoints[3].x = this.surfer.position.x + Surfer.radius * 2;

    this.wave.update();

    this.items.update(this.surfer);

    // this.bgm.rate(1 + (GLOBAL.gameSpeed - 1) * 1.5);
    this.bgm.rate(GLOBAL.gameSpeed);
    // this.bgm.rate(0.5);
  }

  leave() {
    this.items.clear();

    window.removeEventListener('keyup', this.handleKeyUp);
    window.removeEventListener('keydown', this.handleKeyDown);
  }

  handleKeyDown = (e) => {
    if (e.keyCode === 37 || e.keyCode === 65) {
      this.keys.left = true;
    }
    if (e.keyCode === 39 || e.keyCode === 68) {
      this.keys.right = true;
    }
  };

  handleKeyUp = (e) => {
    if (e.keyCode === 37 || e.keyCode === 65) {
      this.keys.left = false;
    }
    if (e.keyCode === 39 || e.keyCode === 68) {
      this.keys.right = false;
    }
  };

  collisionHandler = (itemValue) => {
    if (itemValue < 0) {
      if (this.lives > 0) {
        this.lives -= 1;
        this.surfer.hit();
        this.hitSound.play();
      }
      else {
        const tl = new TimelineMax();

        tl.add(this.surfer.kill());
        tl.to(this.filterNode.frequency, 1, {value: 0, ease: Linear.easeNone}, 0);
        tl.add(() => {
          this.bgm.stop();
          this.gameOverHandler(this.score);
        });

        this.hitSound.play();

        return;
      }
    }
    else if (itemValue > 0) {
      this.score += itemValue;
      this.surfer.score();
      this.scoreSound.play();
    }

    this.updateUI();
  };

  updateUI() {
    this.html.innerHTML = `
      <div class="life-display">
        <div class="live-item ${this.lives > 0 ? '' : 'depleted'}"></div>
        <div class="live-item ${this.lives > 1 ? '' : 'depleted'}"></div>
        <div class="live-item ${this.lives > 2 ? '' : 'depleted'}"></div>
      </div>
      <div class="score-display">${this.score || '000'}</div> 
    `;
  }
}

// End state

class EndState {

  score = 0;

  constructor(params) {
    this.webgl = new THREE.Group();
    this.html = document.createElement('div');
    this.html.className = 'flex-container';

    this.gameStartHandler = params.gameStartHandler;
  }

  enter() {
    this.html.innerHTML = `
      <div class="title">GAME OVER!</div>
      <div class="score"> >> ${this.score} POINTS << </div>
      <div class="button">PLAY AGAIN</div>
    `;

    this.button = this.html.querySelector('.button');
    this.button.addEventListener('click', this.gameStartHandler);
  }

  update() {}

  leave() {
    this.button.removeEventListener('click', this.gameStartHandler);
  }

  setScore(score) {
    this.score = score;
  }
}

// Game class (where it all comes together)

class Game {
  constructor() {
    // setup three
    this.root = new THREERoot({
      createCameraControls: false,
      zNear: 0.01,
      zFar: 1000,
      antialias: true
    });

    this.root.renderer.setClearColor(GLOBAL.colors.yellow);

    GLOBAL.anisotropy = this.root.renderer.capabilities.getMaxAnisotropy();

    // get dom node
    this.html = document.querySelector('#ui-container');

    // create states
    this.startState = new StartState({
      gameStartHandler: this.gameStartHandler
    });

    this.playState = new PlayState({
      gameOverHandler: this.gameOverHandler,
      camera: this.root.camera,
    });

    this.endState = new EndState({
      gameStartHandler: this.gameStartHandler
    });

    // set initial state
    this.enterState(this.startState);

    // start the update loop
    this.root.addUpdateCallback(this.update);
  }

  enterState(state) {
    if (this.currentState) {
      this.currentState.leave();
      this.root.remove(this.currentState.webgl);
      this.html.innerHTML = '';
    }

    this.currentState = state;
    this.currentState.enter();
    this.root.add(this.currentState.webgl);
    this.html.appendChild(this.currentState.html);
  }

  update = () => {
    this.currentState.update();
  };

  gameStartHandler = () => {
    this.enterState(this.playState);
  };

  gameOverHandler = (score) => {
    this.endState.setScore(score);
    this.enterState(this.endState);
  };
}

// Rad!

new Game();

              
            
!
999px

Console