css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/r79/examples/js/controls/OrbitControls.js"></script>
            
          
!
            
              // cannonjsのhelloWorld (https://github.com/schteppe/cannon.js)

// stateはこのstateObjectに突っ込む
const state = {}

let lastTime
const fixedTimeStep = 1.0 / 60.0 // seconds
const maxSubSteps = 10

// 定数はPROPSで管理する。 PROPS().valueName で取得
const PROPS = () => ({
  initPoint: {x: 0,y: 0,z: 0},
  amount: 500,
  initWeight: 1,
  initMass: 2,
  margin: 20,
  limit: 2,
  width: 100,
  height: 100,
  floorColor: "#23372f",
})

window.onload = function() {
  init()
  render()
  animate(0)
}

function init() {
  // init World
  world = state.world = new CANNON.World()
  world.gravity.set(0, -9.82, 0) // m/s²

  // set
  scene = state.sence = new THREE.Scene()
  camera = state.camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    1,
    10000
  )
  camera.position.set(20, 30, 30)

  // generate object
  generate()

  // light
  const ambient = new THREE.AmbientLight(0xffffff, 1.0)
  scene.add(ambient)
  const direction = new THREE.DirectionalLight(0xffffff, 1)
  scene.add(direction)

  // controls ------------------------------
  controls = state.controls = new THREE.OrbitControls(camera)
  controls.maxDistance = 5000.0
  controls.autoRotate = false
  controls.autoRotateSpeed = 1.0

  renderer = state.renderer = new THREE.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)

  document.body.appendChild(renderer.domElement)

  // helper
  const gridHelper = new THREE.GridHelper(1000, 20) // size, step
  scene.add(gridHelper)
  const axisHelper = new THREE.AxisHelper(1000, 50)
  scene.add(axisHelper)
  // X軸が赤色、Y軸が緑色、Z軸が青色
}

function Ground(size = 1000) {
  // cannon
  const body = new CANNON.Body({
    mass: 0 // mass == 0 makes the body static
  })
  body.addShape(new CANNON.Plane())
  //
  body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
  // three
  const geometry = new THREE.PlaneGeometry(size, size)
  const material = new THREE.MeshBasicMaterial({
    color: PROPS().floorColor,
    side: THREE.DoubleSide
  })
  const mesh = new THREE.Mesh(geometry, material)
  mesh.rotation.x = -Math.PI / 2
  mesh.position.y = 0

  return {
    body,
    mesh
  }
}

/**
 * 箱作る
 * @return {body, mesh} ThreejsのmeshとCannon.jsのbodyを返す
 */
function Box(props) {
  const {point,weight, mass = 5,color = 0xaa0000} = props
  //body
  var body = new CANNON.Body({
    mass, // kg
    position: new CANNON.Vec3(point.x, point.y, point.z), // m
    shape: new CANNON.Box(new CANNON.Vec3(weight / 2, weight / 2, weight / 2))
  })
  body.angularVelocity.set(Math.random(), Math.random(), 0)
  // mesh
  var geometry = new THREE.BoxGeometry(weight, weight, weight)
  var material = new THREE.MeshStandardMaterial({
    color,
    roughness: 0.0
  })
  var mesh = new THREE.Mesh(geometry, material)
  mesh.position.set(point.x, point.y, point.z)
  return { body, mesh }
}

/**
 * 球作る
 * @return {body, mesh} ThreejsのmeshとCannon.jsのbodyを返す
 */
function Sphere(props) {
  const {point,weight, mass = 5, color = 0xaa0000} = props
  //body
  var radius = 1 // m
  var body = new CANNON.Body({
    mass, // kg
    position: new CANNON.Vec3(point.x, point.y, point.z), // m
    shape: new CANNON.Sphere(weight)
  })
  // mesh
  const geometry = new THREE.SphereGeometry(weight)
  const material = new THREE.MeshStandardMaterial({
    color,
    roughness: 0.0
  })
  const mesh = new THREE.Mesh(geometry, material)
  mesh.position.set(point.x, point.y, point.z)
  return {
    body,
    mesh
  }
}
/**
 * 円柱作る
 * @return {body, mesh} ThreejsのmeshとCannon.jsのbodyを返す
 */
function Cylinder(props) {
  var { point, weight, mass = 5, color = 0xaa0000 } = props
  //body
  const body = new CANNON.Body({
    mass,
    position: new CANNON.Vec3(point.x, point.y, point.z), // m
    shape: new CANNON.Cylinder(weight, weight, 2 * weight, 10)
  })
  body.angularVelocity.set(Math.random(), Math.random(), 0)
  // mesh
  const geometry = new THREE.CylinderGeometry(weight, weight, weight)
  const material = new THREE.MeshStandardMaterial({
    color,
    roughness: 0.0
  })
  const mesh = new THREE.Mesh(geometry, material)
  mesh.position.set(point.x, point.y, point.z)
  return {
    body,
    mesh
  }
}

function generate(props = {}) {
  // 床
  const ground = (state.ground = new Ground(1000));
  scene.add(ground.mesh);
  world.addBody(ground.body);
  const weight = PROPS().initWeight;
  state.boxes = [];
  
  const rand = (num = 100 ) => Math.floor(Math.random() * num)
  console.log(rand())
  const randcolor = () => new THREE.Color(`hsl(${rand(30)}, ${rand(20) + 80}%, 50%)`)

  for (let i = 0; i < PROPS().amount; i++) {
    function randScale() {
      return (-0.5 + Math.random()) * 10;
    }
    const randPoint = {
      x: randScale(),
      y: randScale(),
      z: randScale()
    }
    const boxPosition = {
      x: randPoint.x,
      y: 10 + i * PROPS().initWeight * 2,
      z: randPoint.z
    }
    var seed = Math.random()
    if (seed < 0.3) {
      state.boxes[i] = new Box({
        point: boxPosition,
        weight: weight,
        mass: 100,
        color: randcolor()
      });
    } else if (seed < 0.6) {
      state.boxes[i] = new Sphere({
        point: boxPosition,
        weight: weight/2,
        mass: 5,
        color: randcolor()
      })
    } else {
      state.boxes[i] = new Cylinder({
        point: boxPosition,
        weight: weight,
        mass: 0.5,
        color: randcolor()
      })
    }
    scene.add(state.boxes[i].mesh)
    world.addBody(state.boxes[i].body)
  }
}

function animate(time) {
  requestAnimationFrame(animate);
  const { boxes } = state
  if (lastTime !== undefined) {
    var dt = (time - lastTime) / 1000;
    world.step(fixedTimeStep, dt, maxSubSteps);
  }
  for (let i = 0; i < PROPS().amount; i++) {
    const { mesh, body } = boxes[i]
    mesh.position.copy(body.position)
    mesh.quaternion.copy(body.quaternion)
  }
  lastTime = time
  render()
}

function render() {
  renderer.render(scene, camera)
}
            
          
!
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