Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <link href="https://fonts.googleapis.com/css2?family=Baloo+Tamma+2&display=swap" rel="stylesheet">
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.js"></script>
<script src="//cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
              
            
!

CSS

              
                * {
  margin: 0;
}

              
            
!

JS

              
                let camera, portalCamera, scene, renderer, controls, keys = {}, assets = {}, portals = [], portalsGroup, ui, hero, onWorldUpdate;

const MathPI2 = Math.PI / 2;
const maps = [
  'e5483900-aedb-4270-a2d1-ef849ea0a375.png',
  'e5483900-aedb-4270-a2d1-ef849ea0a375.png',
  'e5483900-aedb-4270-a2d1-ef849ea0a375.png',

  '73ed30df-1dc1-4f36-9a1b-3d1ecd1b50ad.png',

  '8d1f6fe7-043d-464e-b8ac-3c219ec11dac.png',
  '8d1f6fe7-043d-464e-b8ac-3c219ec11dac.png',
  '8d1f6fe7-043d-464e-b8ac-3c219ec11dac.png',
  '8d1f6fe7-043d-464e-b8ac-3c219ec11dac.png',
  '8d1f6fe7-043d-464e-b8ac-3c219ec11dac.png',
];
const mapId = Math.floor(Math.random() * maps.length); // Note: Set to specific map ID

const createAssets = () => {
  // Meshes
  assets.worldGroundMesh = new THREE.Mesh(
    new THREE.BoxBufferGeometry(1, .1, 1),
    new THREE.MeshStandardMaterial({ color: 0xeeeeee })
  );
  assets.worldWallMesh = new THREE.Mesh(
    new THREE.BoxBufferGeometry(1, 5, 1),
    new THREE.MeshStandardMaterial({ color: 0x555555 })
  );
  assets.worldPortalMesh = new THREE.Mesh(
    new THREE.BoxBufferGeometry(1, 5, 1, 32, 32, 32),
    new THREE.MeshBasicMaterial({ color: 0x555555 })
  );
  assets.worldHeroMock = new THREE.Mesh(
    new THREE.BoxBufferGeometry(.75, .75, .75),
    new THREE.MeshStandardMaterial({ color: 0xff9999 })
  );
  
  // Materials
  assets.worldGroundMaterials = [
    new THREE.MeshStandardMaterial({ color: 0xeeeeee - 0x333333 }),
    new THREE.MeshStandardMaterial({ color: 0xeeeeee - 0x222222 }),
    new THREE.MeshStandardMaterial({ color: 0xeeeeee - 0x111111 })
  ];
  
  assets.portalShaderMaterial = new THREE.ShaderMaterial({
    uniforms: {
      resolution: {
        value: new THREE.Vector2(window.innerWidth, window.innerHeight),
      },
      opacity: {
        value: 1.0,
      },
      dt: {
        value: 0.0
      },
      map: {
        type: "t",
        value: null
      },
    },
    vertexShader: `
      uniform float dt;

      varying vec2 uVu;
      varying vec4 pos;

      void main() {
        uVu = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
        gl_Position.x += sin(.1 * dt + 10. * position.y) * .1;
        pos = gl_Position / gl_Position.w;
      }
    `,
    fragmentShader: `
      uniform sampler2D map;
      uniform vec4 resolution;
      uniform float opacity;

      varying vec2 uVu;
      varying vec4 pos;

      void main() {
        vec2 uv = pos.xy * .5 + .5;
        vec4 tex = texture2D(map, uv);
        gl_FragColor = opacity * tex;

        if (abs(.5 - uVu.y) >= .499 || abs(.5 - uVu.x) >= .49) {
          gl_FragColor += vec4(.5);
        }
      }
    `,
    transparent: true,
  });
  
  // Async assets
  return Promise.all([
    new Promise(resolve => {
      assets.mapTexture = new THREE.TextureLoader().load(`//cdn.wtlstudio.com/common-ptr.wtlstudio.com/${maps[mapId]}`, texture => {
        texture.magFilter = THREE.NearestFilter;
        texture.minFilter = THREE.NearestFilter;
        
        resolve();
      });
    }),
  ]);
};

const createPortal = (x, z) => {
  const tile = assets.worldPortalMesh.clone();
  tile.material = assets.portalShaderMaterial.clone();
  tile.position.set(x, 0, z);
  
  const portal = {
    tile,
    targetPortal: null
  };

  portal.onPortalUpdate = () => {
    if (!portal.targetPortal && portals.length > 1) {
      while (!portal.targetPortal) {
        const randomIndex = Math.floor(Math.random() * portals.length);

        if (portals[randomIndex].tile !== tile) {
          portal.targetPortal = portals[randomIndex];
        }
      }
    }
  };

  portals.push(portal);

  return tile;
};

const createWorld = () => {
  const worldSize = [
    assets.mapTexture.image.naturalWidth || assets.mapTexture.image.width,
    assets.mapTexture.image.naturalHeight || assets.mapTexture.image.height
  ];
  ui = new THREE.Group();
  scene.add(ui);

  const mapView = new THREE.Mesh(
    new THREE.PlaneBufferGeometry(.25, .25, 1, 1),
    new THREE.MeshBasicMaterial({ map: assets.mapTexture })
  );
  mapView.rotation.x = -MathPI2;
  mapView.renderOrder = 1;
  ui.add(mapView);

  const worldMap = new THREE.Group();
  const worldNavHash = {};
  const worldParserCanvas = document.createElement('canvas');
  const worldParserCanvasCtx = worldParserCanvas.getContext('2d');
  worldParserCanvasCtx.drawImage(assets.mapTexture.image, 0, 0);
  const worldTiles = worldParserCanvasCtx.getImageData(0, 0, worldSize[0], worldSize[1]);

  hero = assets.worldHeroMock.clone();
  hero.position.set(0, .5, 0);

  portalsGroup = new THREE.Group();
  worldMap.add(portalsGroup);
  
  worldMap.add(hero);

  for (let i = 0; i < worldTiles.data.length; i += 4) {
    const p = i / 4;
    const x = p % worldSize[0];
    const z = Math.floor(p / worldSize[0]);
    const r = worldTiles.data[i];
    const g = worldTiles.data[i + 1];
    const b = worldTiles.data[i + 2];
    let tile;

    tile = assets.worldGroundMesh.clone();
    tile.position.set(x, Math.random() * .1, z);
    tile.material = assets.worldGroundMaterials[Math.floor(Math.random() * assets.worldGroundMaterials.length)].clone();
    tile.material.color.b += z / 200;
    tile.material.color.r += x / 200;

    worldMap.add(tile);

    if ((r | g | b) === 0) {
      // Walls
      tile = assets.worldWallMesh.clone();
      tile.position.set(x, 0, z);
      worldMap.add(tile);
      
      worldNavHash[`${x}x${z}`] = false;
    } else if (r && (g | b) === 0) {
      // Portal (red)
      const tile = createPortal(x, z);
      portalsGroup.add(tile);
    } else if (g && (r | b) === 0) {
      // Portal (spawn point)
      tile = assets.worldGroundMesh.clone();
      tile.position.set(x, .15, z);
      tile.material = tile.material.clone();
      tile.material.color = new THREE.Color(0x99ff99);
      worldMap.add(tile);

      hero.position.x = tile.position.x;
      hero.position.z = tile.position.z;
    } else if (b && (r | g) === 0) {
      // Portal (blue)
      const tile = createPortal(x, z, portals);
      portalsGroup.add(tile);
    }
  }

  scene.add(worldMap);

  onWorldUpdate = () => {
    portals.forEach(({ onPortalUpdate }) => 
      typeof onPortalUpdate === 'function' && onPortalUpdate(portals)
    );

    const cameraDirection = new THREE.Vector3();
    camera.getWorldDirection(cameraDirection);

    controls.target = hero.position;
    
    if (keys['w'] | keys['a'] | keys['s'] | keys['d']) {
      const heroSpeed = .25;
      const heroDirection = new THREE.Vector3(0, 0, 0);
      
      if (keys['w']) {
        heroDirection.add(cameraDirection.clone().multiplyScalar(heroSpeed));
      }
      
      if (keys['s']) {
        heroDirection.add(cameraDirection.clone().multiplyScalar(-heroSpeed));
      }
      
      if (keys['a']) {
        heroDirection.add(cameraDirection.clone().applyAxisAngle(new THREE.Vector3(0, 1, 0), MathPI2).multiplyScalar(heroSpeed));
      }
      
      if (keys['d']) {
        heroDirection.add(cameraDirection.clone().applyAxisAngle(new THREE.Vector3(0, 1, 0), MathPI2).multiplyScalar(-heroSpeed));
      }

      heroDirection.y = 0;
      const nextPosition = hero.position.clone().add(heroDirection);
      const nextPositionBox = nextPosition.clone().add(heroDirection.normalize().multiplyScalar(.375));
      const nextPositionX = Math.round(nextPositionBox.x);
      const nextPositionZ = Math.round(nextPositionBox.z);
      
      if (worldNavHash[`${nextPositionX}x${nextPositionZ}`] !== false) {
        hero.position.copy(nextPosition);
      }
    }
    
    const heroRotation = hero.quaternion.clone().slerp(camera.quaternion.clone(), .25);
    heroRotation.x = 0;
    heroRotation.z = 0;
    hero.quaternion.copy(heroRotation);
    mapView.position.copy(camera.position.clone().add(cameraDirection.clone().multiplyScalar(.5)));
    mapView.position.add(cameraDirection.clone().applyAxisAngle(new THREE.Vector3(0, 1, 0), MathPI2).multiplyScalar(.5));
    mapView.position.y = camera.position.y - 1;
  };
};

const init = () => {
  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000.0);
  camera.position.set(0, 2, 7);
  
  portalCamera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100.0);

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x333333);

  scene.add(new THREE.HemisphereLight(0xffffcc, 0x19bbdc, 1));

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.domElement.tabIndex = 1;

  document.body.appendChild(renderer.domElement);
  
  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.maxPolarAngle = 0.6;
  controls.minPolarAngle = 0.6;
  controls.minDistance = 10.0;
  controls.maxDistance = 10.0;
  controls.enablePan = false;
  controls.enableZoom = false;
  controls.enableKeys = false;
  
  createAssets().then(() => createWorld());
  
  document.body.addEventListener('keydown', (e) => keys[e.key.toLowerCase()] = true);
  document.body.addEventListener('keyup', (e) => keys[e.key.toLowerCase()] = false);
}

const animate = () => {
  requestAnimationFrame(animate);
  
  controls.update();

  if (typeof onWorldUpdate === 'function') {
    onWorldUpdate();
  }

  portalCamera.quaternion.copy(camera.quaternion);

  portals.forEach(portal => {
    const { tile, targetPortal, renderTarget } = portal;

    if (renderTarget) {
      portal.renderTarget.dispose();
    }
    
    const cameraHeroOffset = camera.position.clone().sub(hero.position);
    const cameraTileOffset = camera.position.clone().sub(tile.position);
    const heroOffset = tile.position.clone().sub(hero.position.clone());

    portal.renderTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);

    portalCamera.copy(camera, false);
    portalCamera.position.copy(targetPortal.tile.position);
    portalCamera.position.y = camera.position.y;
    portalCamera.position.x -= hero.position.x - camera.position.x;
    portalCamera.position.z -= hero.position.z - camera.position.z;

    renderer.setRenderTarget(portal.renderTarget);
    renderer.clear();

    portalsGroup.visible = false;
    ui.visible = false;
    renderer.render(scene, portalCamera);
    portalsGroup.visible = true;
    ui.visible = true;
    
    if (heroOffset.length() < .75 && tile.material.uniforms.opacity.value >= 0.75) {
      const teleportedPosition = targetPortal.tile.position.clone();
      teleportedPosition.y = hero.position.y;
      hero.position.copy(teleportedPosition);
      camera.position.copy(hero.position).add(cameraHeroOffset);

      targetPortal.tile.material.uniforms.opacity.value = -1.0;
    }

    tile.material.uniforms.map.value = portal.renderTarget.texture;
    tile.material.uniforms.dt.value += 1;
    
    if (tile.material.uniforms.opacity.value < 1.0) {
      tile.material.uniforms.opacity.value = THREE.MathUtils.lerp(tile.material.uniforms.opacity.value, 1.0, .05);
    }
  });

  renderer.setRenderTarget(null);
  renderer.clear();
  renderer.render(scene, camera);
}

init();
animate();

              
            
!
999px

Console