cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

            
              <script>console.clear();</script>
            
          
!
            
              canvas { display: block; }
            
          
!
            
              
const backgroundColor = 0x222222;//FFFFFF;
const HALFPI = Math.PI / 2;
const TWOPI = Math.PI * 2;

/*////////////////////////////////////////*/

var renderCalls = [];
function render () {
  requestAnimationFrame( render );
  renderCalls.forEach((callback)=>{ callback(); });
}
render();

/*////////////////////////////////////////*/

initCannon();

var scene = new THREE.Scene();
scene.fog = new THREE.Fog(backgroundColor, 100, 250);

var camera = new THREE.PerspectiveCamera( 80, window.innerWidth / window.innerHeight, 0.1, 800 );
camera.position.z = 30;
camera.position.y = 10;

var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( backgroundColor );//0x );

renderer.toneMapping = THREE.LinearToneMapping;
renderer.toneMappingExposure = Math.pow( 0.94, 5.0 );
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;

window.addEventListener( 'resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize( window.innerWidth, window.innerHeight );
}, false );

document.body.appendChild( renderer.domElement );

renderCalls.push(function(){ renderer.render( scene, camera ); });

/*////////////////////////////////////////*/

var orbit = new THREE.OrbitControls(camera, renderer.domElement);
camera.lookAt(orbit.target = new THREE.Vector3(0,12,0));

// orbit.enabled = true;

/*////////////////////////////////////////*/

var ambientLight = new THREE.AmbientLight(0x444444);
scene.add(ambientLight);

var light = new THREE.SpotLight(0xFFFFFF, 1, 400); //SpotLight( 0xffffff );
light.position.y = 120;
light.position.z = 10;
light.power = 1;
light.angle = Math.PI / 2.5; //Math.PI / 4;

light.castShadow = true;
light.shadow.mapSize.width = 4096;
light.shadow.mapSize.height = 4096;
light.shadow.camera.near = 0.1;
light.shadow.camera.far = 300;
light.shadow.camera.fov = 20;

scene.add( light );

var fillLight = new THREE.SpotLight(0xFFFFFF, 1, 400); //SpotLight( 0xffffff );
fillLight.position.y = 10;
fillLight.position.x = 0;
fillLight.position.z = 85; //110;
fillLight.power = 3;
scene.add(fillLight);

// var fillLight = new THREE.PointLight(0xFFFFFF, 1, 400); //SpotLight( 0xffffff );
// fillLight.position.y = 10;
// fillLight.position.z = 10;
// fillLight.power = 5;

// scene.add( fillLight );

var hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.3 );
hemiLight.color.setHSL( 0.6, 1, 0.6 );
hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
hemiLight.position.set( 0, 0, 0 );
scene.add( hemiLight );

/*////////////////////////////////////////*/

var world;
const dt = 1 / 60;

var constraintDown = false;
var controls, time = Date.now();

function initCannon(){
  // Setup our world
  world = new CANNON.World();
  world.quatNormalizeSkip = 0;
  world.quatNormalizeFast = false;
  world.allowSleep = true;

  world.gravity.set(0,-10,0);
  world.broadphase = new CANNON.NaiveBroadphase();
}

function updatePhysics(){ world.step(dt); }
renderCalls.push(updatePhysics);

/*////////////////////////////////////////*/

function noiseMap(size,intensity){
  var canvas = document.createElement('canvas'),
      ctx = canvas.getContext('2d'),
      width = canvas.width = size || 512,
      height = canvas.height = size || 512;

  intensity = intensity || 120;

  var imageData = ctx.getImageData(0, 0, width, height),
      pixels = imageData.data,
      n = pixels.length,
      i = 0;

  while (i < n) {
    pixels[i++] = pixels[i++] = pixels[i++] = Math.sin( i * i * i + (i/n) * Math.PI) * intensity; 
    pixels[i++] = 255;
  }
  ctx.putImageData(imageData, 0, 0);

  let sprite = new THREE.Texture(canvas);
  sprite.needsUpdate = true;

  return sprite;
}

/*////////////////////////////////////////*/

const toastHeight = 8;
const toastWidth = 8;
const toastDepth = 1;

const toastHeightSegments = 8;
const toastWidthSegments = 5;
const toastGeo = new THREE.BoxGeometry( toastWidth, toastHeight, toastDepth, toastWidthSegments, toastHeightSegments );

toastGeo.vertices.forEach((vertex,i)=>{
  let offsetX = (vertex.y * -0.06);
  let offsetY = 0;

  if ( vertex.y === toastHeight / 2 ) {
    offsetY = -0.4 + 0.5 * Math.cos((vertex.x / (toastWidthSegments-1)) * HALFPI);
    offsetX = ( Math.abs(vertex.x) > 1 ? -0.5 : -0.25 );
  } else if ( vertex.y > (toastHeight / 2) * 0.25 ) {// (toastHeightSegments/2) ) {
    offsetX = 0.4 * Math.sin((vertex.y / (toastHeightSegments /2)) * Math.PI);
  }

  vertex.x += offsetX * ( vertex.x < 0 ? -1 : 1 );
  vertex.y += offsetY;
});

// Color the outside of the toast
let color = 0x630A10; //Math.random() * 0xffffff;
for (var i = 0; i < (toastHeightSegments * 4) + ( toastWidthSegments * 4); i++) {
  toastGeo.faces[i].color.setHex( color );
}

var toastMaterial = new THREE.MeshStandardMaterial( { 
  color: 0xFFDD83, //0xFFDD83, 
  vertexColors: THREE.FaceColors,
  roughness: 1,
  //bumpMap: noiseMap(256,10),
  //bumpMapScale: 0.2,
  metalness: 0,

});

function Toast(){
  THREE.Mesh.call(this, toastGeo, toastMaterial);
};

Toast.prototype = Object.create(THREE.Mesh.prototype);


/*////////////////////////////////////////*/


function PhysicalBox(opts) {

  if (!(this instanceof PhysicalBox)) { return new PhysicalBox(opts); }

  opts = opts || this.defaultOpts;
  CANNON.Body.call(this, opts);

  this.object = new THREE.Object3D();
  this.sync = this.sync.bind(this);
}

PhysicalBox.prototype = Object.assign(Object.create(CANNON.Body.prototype),{
  constructor: PhysicalBox,

  defaultOpts: { mass: 100 },

  add: function(obj){
    this.object.add(obj); //.apply(this.object, arguments);
    this.updateShape();
  },

  updateShape: function(){
    let bbox = new THREE.Box3().setFromObject(this.object);
    this.shapes = [];
    this.addShape(new CANNON.Box( new CANNON.Vec3( bbox.max.x, bbox.max.y, bbox.max.z) ));
  },

  sync: function(){
    if ( this.position && this.object ) {
      this.object.position.copy( this.position );
      this.object.quaternion.copy( this.quaternion );
    }
  }
});


/*////////////////////////////////////////*/

function makeGround(){

  let geometry = new THREE.PlaneGeometry( 1000, 300, 1, 1 );
  let material = new THREE.MeshPhongMaterial({ 
    color: backgroundColor, 
    emissive: backgroundColor,
    emissiveIntensity: 0.7,
    // transparent: true,
    // opacity: 0.8,
    shininess: 680,
    shading: THREE.SmoothShading
  }); 

  material.color.offsetHSL(0,0,0.15);

  mesh = new THREE.Mesh( geometry, material );
  //plane.rotation.x = Math.PI / -2;
  mesh.castShadow = true;
  mesh.receiveShadow = true;
  mesh.quaternion.setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI / 2);
  scene.add(mesh);

  // Create a plane
  var groundShape = new CANNON.Plane();
  var groundBody = new CANNON.Body({ mass: 0 });
  groundBody.addShape(groundShape);
  groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
  world.add(groundBody);

}
makeGround();

/*////////////////////////////////////////*/

const wallMaterial = new THREE.MeshBasicMaterial({ color: 0xFF0000, transparent: true, opacity: 0 });

function makeWall(width = 200, height = 50){
  var c3d = new PhysicalBox({ mass: 0 });

  world.add(c3d);
  scene.add(c3d.object);

  var wallGeometry = new THREE.BoxGeometry( width, height, 1 );

  var wallMesh = new THREE.Mesh( wallGeometry, wallMaterial );
  c3d.add(wallMesh);

  renderCalls.push(c3d.sync);

  return c3d;
}

function makeWalls(){

  for (let i = 0, len = 4; i < len; i++){
    let width = 140;
    let height = 60;
    let depth = 12;
    let x = 0;
    let z = 0;
    let y = height/2;

    if ( i % 2 !== 0 ) {
      x = (width/2) * ( i < len/2 ? -1 : 1 );
      width = depth*2;
    } else {
      z = depth * ( i < len/2 ? -1 : 1 );
    }

    let c3d = makeWall(width, height);
    c3d.position.set(x,y,z);
    c3d.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0),(TWOPI) * i/len);
  }
}

makeWalls();




/*////////////////////////////////////////*/

var len = 20,
    toasts = Array(len).fill(null);

toasts.forEach((c3d,i)=>{

  c3d = new PhysicalBox({ mass: 100 });

  let toast = new Toast();
  toast.castShadow = true;
  //toast.receiveShadow = true;
  c3d.add(toast);

  renderCalls.push(c3d.sync);

  c3d.position.set( 
    40 * Math.sin(((i / len) * Math.PI) - HALFPI), 
    45 + i*6, //( i % 2 ? -4 : 4),
    0//(i % 2 ? -4 : 4)
  );

  c3d.quaternion.setFromEuler(
    Math.random() * HALFPI/2, 
    HALFPI,//Math.PI, 
    0//Math.random() * HALFPI/4
  );

  c3d._bounce = function(){
    // Shoot into the air
    c3d.velocity.set(
      0, 
      25 + (Math.random() * 10), 
      2 * (Math.random() - 0.5)
    );

    // Spin
    c3d.angularVelocity.set(
      (Math.random() - 0.5) * Math.PI, 
      (Math.random() - 0.5) * Math.PI,
      (Math.random() - 0.5) * Math.PI
    );
  }

  renderCalls.push(()=>{
    // If the toast is near the ground or sleeping
    if ( c3d.position.y < 4 || c3d.SLEEPING ) {
      c3d._bounce();
    }
  });

  c3d.allowSleep = true;
  c3d.sleepSpeedLimit = 0.8;
  c3d.addEventListener("sleepy",function(event){

    // If the toast is near the ground or sleeping
    if ( c3d.position.y < 10 || c3d.SLEEPING ) {
      c3d._bounce();
    }
  });

  
  scene.add(c3d.object);
    world.add(c3d);


});


            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console