123

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.

            
                <div class="levelContainer">
    <div id="levelBar"></div>
  </div>
<!--   <textarea name="" id="record" rows="10"></textarea> -->

<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.2/dat.gui.js"></script>
            
          
!
            
              .levelContainer {
  width: 100%;
  height: 100%;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
}

#levelBar {
  width: 40%;
  height: 2px;
  margin: auto;
  display: block;
  position: absolute;
  background: aquamarine;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#record {
  position: absolute;
  background: #00000066;
  color: #ccc;
  width: 100%;
  border: none;
}
            
          
!
            
                  // hello2の内容と20180827-2__cannonjsをつなぐ

    const state = {}

    let lastTime
    var fixedTimeStep = 1.0 / 60.0; // seconds
    var maxSubSteps = 10;

    function PROPS() {
      this.initPoint = {
        x: 0,
        y: 0,
        z: 0,
      }
      this.amount = 50
      this.initWeight = 0.1 // meter
      this.initLength = 0.3 // meter
      this.margin = 0.2 // meter
      this.rotate = {
        x: 0,
        y: 0,
        z: 0,
      }
      this.axis_rotate = 0
      this.limit = 2
      this.width = 100;
      this.height = 100;
      this.color1 = "#23372f"
      this.ground = {
        color: "#23372f",
        position_y: 0,
        rotation_x: 0,
        rotation_y: 0,
      }
    }

    window.onload = function () {
      datProps = new PROPS();
      const gui = new dat.GUI();
      const ground = gui.addFolder('ground')
      ground.addColor(datProps.ground, 'color').onChange(e => {
        const color = new THREE.Color(e)
        state.ground.mesh.material.color = color
      });
      ground.add(datProps.ground, 'position_y', -10, 20).onChange(e => {
        state.ground.body.position.y = e
      });
      // ground.add(datProps.ground, 'rotation_x', -60, 60).onChange(e => updateGround(e, 'x'))
      // ground.add(datProps.ground, 'rotation_y', -60, 60).onChange(e => updateGround(e, 'y'))
      function updateGround(e, key) {
        if (key === 'x') {
          state.ground.body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Degree2Radian(e - 90));
        }
      }
      ground.open()

      init()
      render()
      animate(0)
      orientation()
      
    }

    function init() {
      // init World
      world = new CANNON.World();
      world.gravity.set(0, -9.82, 0); // m/s²
      world.solver.iterations = 10 // 検証回数
      world.solver.tolerance = 0.1 // 許容誤差
      // set
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
      camera.position.set(4, 2, 0);
      // 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)
      // render
      renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      // controls ------------------------------
      controls = new THREE.OrbitControls(camera, renderer.domElement);
      controls.maxDistance = 5000.0;
      controls.autoRotate = false;
      controls.autoRotateSpeed = 1.0;

      document.body.appendChild(renderer.domElement);
      // helper
      {
        const gridHelper = new THREE.GridHelper(1000, 50); // size, step
        // scene.add(gridHelper);
        const axisHelper = new THREE.AxisHelper(1000, 50);
        scene.add(axisHelper);
        // X軸が赤色、Y軸が緑色、Z軸が青色
      }
    }

    function Ground(props) {
      const {
        size = 100,
        weight = 0.2
      } = props
      // cannon
      const body = new CANNON.Body({
        mass: 0 // mass == 0 makes the body static
      })
      body.addShape(new CANNON.Box(new CANNON.Vec3( size / 2, size / 2, weight/2)))
      body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
      // three
      const geometry = new THREE.BoxGeometry(size, size, weight);
      var material = new THREE.MeshStandardMaterial({
        color: datProps.ground.color,
        side: THREE.DoubleSide,
        roughness: 0.0
      })
      var mesh = new THREE.Mesh(geometry, material)
      mesh.rotation.x = -Math.PI / 2;
      mesh.position.y = 0;
      return {
        body,
        mesh
      }
    }

    function Box(props) {
      const {
        point,
        weight,
        color = 0xAA0000
      } = props
      //body
      var body = new CANNON.Body({
        mass: 0.1, // 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
      const geometry = new THREE.BoxGeometry(weight, weight, weight);
      const material = new THREE.MeshStandardMaterial({
        color: color,
        roughness: 0.0
      })
      const mesh = new THREE.Mesh(geometry, material)
      mesh.position.set(point.x, point.y, point.z)
      return {
        body,
        mesh
      }
    }

    function Sphere(props) {
      const {
        point,
        weight,
        color = 0xAA0000
      } = props
      //body
      var radius = 1; // m
      var body = state.sphere = new CANNON.Body({
        mass: 50, // 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: color,
        roughness: 0.0
      })
      const mesh = new THREE.Mesh(geometry, material);
      mesh.position.set(point.x, point.y, point.z);
      return {
        body,
        mesh
      }
    }

    function Cylinder(props) {
      const {
        point,
        weight,
        color = 0xAA0000
      } = props
      //body
      const body = new CANNON.Body({
        mass: 1,
        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: 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({
        size: 10
      })
      scene.add(ground.mesh);
      world.addBody(ground.body);
      const {
        point = datProps.initPoint,
          generation = 0,
      } = props
      const weight = datProps.initWeight;
      const length = datProps.initLength;
      state.boxes = []
      state.boxesState = []
      for (let i = 0; i < datProps.amount; i++) {
        // randPoint = datProps.initPoint
        const randPoint = {
          x: randScale(1),
          y: randScale(1),
          z: randScale(1),
        }
        const boxState = state.boxesState[i] = {
          ...state.boxesState[i],
          seed: Math.random(),
        }
        const boxPosition = {
          x: randPoint.x,
          y: 1 + i * datProps.initWeight * 2,
          z: randPoint.z
        }
        const box = state.boxes[i] = i < datProps.amount / 3 ? new Box({
            point: boxPosition,
            weight: weight,
          }) :
          i < datProps.amount * 2 / 3 ?
          new Cylinder({
            point: boxPosition,
            weight: weight,
          }) :
          new Sphere({
            point: boxPosition,
            weight: weight,
          })
        scene.add(box.mesh);
        world.addBody(box.body);
      }
    }

    function orientation() {
      state.deviceorientationFlg = false
      // DeviceOrientation Event
      const record = document.getElementById('record')
      const levelBar = document.getElementById('levelBar')
      // record.value = "hoge"
      levelBar.setAttribute("style", "transform: rotate(10deg)")

      window.addEventListener("deviceorientation", deviceorientationHandler)

      function deviceorientationHandler(e) {
        if (!state.deviceorientationFlg) state.deviceorientationFlg = true
        const beta = e.beta; // X軸
        const gamma = e.gamma; // Y軸
        const alpha = e.alpha; // Z軸
        // record.value = `x:${beta},\ny:${gamma},\nz:${alpha}`
        const rotate = gamma
        levelBar.setAttribute("style", `transform: rotate(${rotate}deg)`)
        state.ground.body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Degree2Radian(-1 * rotate - 90));
      }

      document.addEventListener("mousemove", mousemoveHandler)

      function mousemoveHandler(e) {
        if (state.deviceorientationFlg) return
        if (!state.windowWidth) {
          state.windowWidth = window.innerWidth
          state.windowHeight = window.innerHeight
        }
        const max = 30
        const mX = e.pageX; //X座標
        const mY = e.pageY; //Y座標
        const width = state.windowWidth
        const height = state.windowHeight
        const rotate = (mX / width * max * -2) + max
        // record.value = `x:${mX},\ny:${mY},\nwidth:${width},\nheight:${height},\nrotate:${rotate}`
        levelBar.setAttribute("style", `transform: rotate(${rotate}deg)`)
        state.ground.body.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), Degree2Radian(-1 * rotate - 90));
      }
    }

    function animate(time) {
      requestAnimationFrame(animate);
      const {
        ground,
        boxes
      } = state
      if (lastTime !== undefined) {
        var dt = (time - lastTime) / 1000;
        world.step(fixedTimeStep, dt, maxSubSteps);
      }

      ground.mesh.position.copy(ground.body.position);
      ground.mesh.quaternion.copy(ground.body.quaternion);

      for (let i = 0; i < datProps.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);
    }
    const randScale = (scale = 1) => ((-0.5 + Math.random()) * scale)
    const Degree2Radian = (degree) => (degree * (Math.PI / 180))
    const Radian2Degree = (radian) => (radian * (180 / Math.PI))
            
          
!
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.

Console