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

              
                <script type="importmap">
  {
    "imports": {      
      "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
      "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
    }
  }
</script>
    <script src="https://cdn.jsdelivr.net/gh/kripken/ammo.js@HEAD/builds/ammo.wasm.js"></script>

              
            
!

CSS

              
                body, canvas{
  margin:0;
  padding:0;
  width: 100%;
  height: 100vh;
  display: block;
}
              
            
!

JS

              
                import * as THREE from "three";
import { OrbitControls } from 'three/addons/controls/OrbitControls';

let camera, scene, renderer, orbitControls;

Ammo().then((AmmoLib) => {
  Ammo = AmmoLib;
  init();
  animate();
});

function init3DContext(){

  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.2, 500);
  camera.position.set(0, 5, 10);

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

  renderer = new THREE.WebGLRenderer({antialias: true});
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  document.body.appendChild(renderer.domElement);

  orbitControls = new OrbitControls(camera, renderer.domElement);

  const light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(5, 10, 7.5);
  scene.add(light);

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

  renderer.setSize( window.innerWidth, window.innerHeight );

}

var gravityConstant = -9.8;
var collisionConfiguration;
var dispatcher;
var broadphase;
var solver;
var physicsWorld;
var transformAux1;
function initPhysicsWorld(){
  transformAux1 = new Ammo.btTransform();
  
  
  collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
  broadphase = new Ammo.btDbvtBroadphase();
  solver = new Ammo.btSequentialImpulseConstraintSolver();
  physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  physicsWorld.setGravity(new Ammo.btVector3(0, gravityConstant, 0));
};

var rigidBodies = [];
function createCubesandGround(){
  var pos = new THREE.Vector3();
  var quat = new THREE.Quaternion();

  // creacion del suelo
  pos.set(0, -0.5, 0);
  quat.set(0, 0, 0, 1);
  
  var ground = createParallellepiped(40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial({color: 0xffffff}));
  ground.castShadow = true;       
  ground.receiveShadow = true;    

  // creacion de los cubos
  for (var i = 0; i < 30; i++) {
      pos.set(Math.random(), 2 *i, Math.random());
      quat.set(0, 0, 0, 1);

      createParallellepiped(1, 1, 1, 1, pos, quat, createRandomColorMaterial());
  }
};

// color random de los cubos
function createRandomColorMaterial() {
  var color = Math.floor(Math.random() * (1 << 24));
  return new THREE.MeshPhongMaterial({color: color});
}
var margin = 0.05;
function createParallellepiped(sx, sy, sz, mass, pos, quat, material) {
  var threeObject = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz, 1, 1, 1), material);
  var shape = new Ammo.btBoxShape(new Ammo.btVector3(sx * 0.5, sy * 0.5, sz * 0.5));
  shape.setMargin(margin);

  createRigidBody(threeObject, shape, mass, pos, quat);

  return threeObject;
}

function createRigidBody(threeObject, physicsShape, mass, pos, quat) {
  threeObject.position.copy(pos);
  threeObject.quaternion.copy(quat);

  var transform = new Ammo.btTransform();
  transform.setIdentity();
  transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
  transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w));
  var motionState = new Ammo.btDefaultMotionState(transform);

  var localInertia = new Ammo.btVector3(0, 0, 0);
  physicsShape.calculateLocalInertia(mass, localInertia);

  var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, physicsShape, localInertia);
  var body = new Ammo.btRigidBody(rbInfo);

  threeObject.userData.physicsBody = body;

  scene.add(threeObject);

  // si tiene massa se añade dentro del array d eobjetos
  if (mass > 0) {
      rigidBodies.push(threeObject);
      // Disable deactivation
      body.setActivationState(4);
  }

  physicsWorld.addRigidBody(body);

  return body;
}

function init(){
  init3DContext();

  initPhysicsWorld();

  createCubesandGround();
}
function animate(){
  requestAnimationFrame(animate);

  render();

  renderer.render(scene, camera);
}

var clock = new THREE.Clock();
var time = 0;
function render() {
  var deltaTime = clock.getDelta();

  updatePhysics(deltaTime);

  orbitControls.update(deltaTime);

  renderer.render(scene, camera);

  time += deltaTime;
}

function updatePhysics(deltaTime) {
  physicsWorld.stepSimulation(deltaTime);

  for (var i = 0, iL = rigidBodies.length; i <iL; i++ ){
      var objThree = rigidBodies[i];
      var objPhys = objThree.userData.physicsBody;
      var ms = objPhys.getMotionState();
      if (ms) {
          ms.getWorldTransform(transformAux1);
          var p = transformAux1.getOrigin();
          var q = transformAux1.getRotation();
          objThree.position.set(p.x(), p.y(), p.z());
          objThree.quaternion.set(q.x(), q.y(), q.z(), q.w());
      }
  }
}
              
            
!
999px

Console