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 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>
              
            
!

CSS

              
                
              
            
!

JS

              
                // 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

Console