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.

            
              <html style='margin: 0;height: 100%;'>
<!-- Three.js r106        --><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/106/three.js"></script>
<!-- TrackballControls.js --><script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/controls/TrackballControls.js"></script>
<!-- cannon.js v0.6.2     --><script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js"></script>
<body style='margin: 0;height: 100%;'>
<script>

class THREEJS
{
    constructor()
    {
        const w = document.body.clientWidth
        const h = document.body.clientHeight

        this.renderer = new THREE.WebGLRenderer()
        this.renderer.setClearColor( 0x8888dd )
        this.renderer.setSize( w, h )

        this.camera = new THREE.PerspectiveCamera( 40, w / h, 0.1, 1000 )
        this.camera.position.x =  0
        this.camera.position.y = 20
        this.camera.position.z = 30
        this.trackball = new THREE.TrackballControls( this.camera )

        this.scene = new THREE.Scene()

        let directionalLight = new THREE.DirectionalLight( 0xffffff, 1 )
        directionalLight.position.set( 0.2, 0.5, 0.3 )
        this.scene.add( directionalLight )

        // this.scene.add( new THREE.AmbientLight( 0x101020 ) )

        document.body.appendChild( this.renderer.domElement )
    }

    render()
    {
        for ( let mesh of this.scene.children )
        {
            if ( ! mesh.cannon_rigid_body ) continue

            mesh.position.copy(   mesh.cannon_rigid_body.position   )
            mesh.quaternion.copy( mesh.cannon_rigid_body.quaternion )
        }

        this.trackball.update()
        this.renderer.render( this.scene, this.camera )
    }
}

class CANNON_PHYSICS
{
    constructor( _threejs )
    {
        this.cannon_world = new CANNON.World()
        this.cannon_world.gravity.set( 0, -9.80665, 0 )
        this.cannon_world.broadphase = new CANNON.NaiveBroadphase()
        this.cannon_world.solver.iterations = 10

        this.threejs = _threejs
    }

    add_box( _arg )
    {
        const body  = new CANNON.Body( {
            mass:       _arg.mass,
            shape:      new CANNON.Box( new CANNON.Vec3( _arg.w/2, _arg.h/2, _arg.d/2 ) ),
            position:   new CANNON.Vec3( _arg.x, _arg.y, _arg.z ),
            material:   new CANNON.Material( { friction: 0.1, } ), // 摩擦係数 0.1 マテリアルを作成
        } )
        this.add_body( body, _arg.color )
    }

    add_body( _body, _color )
    {
        this.cannon_world.addBody( _body )

        var obj = new THREE.Object3D();
        const color_mat = new THREE.MeshLambertMaterial( { color: _color } )

        // ここのコードは connon.demo.js の 977 shape2mesh() から、まるっと借りてきた。
        for (var l = 0; l < _body.shapes.length; l++)
        {
            var shape = _body.shapes[l];

            var mesh;

            switch(shape.type)
            {

            case CANNON.Shape.types.SPHERE:
                var sphere_geometry = new THREE.SphereGeometry( shape.radius, 8, 8);
                mesh = new THREE.Mesh( sphere_geometry, color_mat );
                break;

            case CANNON.Shape.types.PARTICLE:
                mesh = new THREE.Mesh( this.particleGeo, this.particleMaterial );
                var s = this.settings;
                mesh.scale.set(s.particleSize,s.particleSize,s.particleSize);
                break;

            case CANNON.Shape.types.PLANE:
                var geometry = new THREE.PlaneGeometry(10, 10, 4, 4);
                mesh = new THREE.Object3D();
                var submesh = new THREE.Object3D();
                var ground = new THREE.Mesh( geometry, color_mat );
                ground.scale.set(100, 100, 100);
                submesh.add(ground);

                ground.castShadow = true;
                ground.receiveShadow = true;

                mesh.add(submesh);
                break;

            case CANNON.Shape.types.BOX:
                var box_geometry = new THREE.BoxGeometry(
                    shape.halfExtents.x*2,
                    shape.halfExtents.y*2,
                    shape.halfExtents.z*2 );
                mesh = new THREE.Mesh( box_geometry, color_mat );
                break;

            case CANNON.Shape.types.CONVEXPOLYHEDRON:
                var geo = new THREE.Geometry();

                // Add vertices
                for (var i = 0; i < shape.vertices.length; i++) {
                    var v = shape.vertices[i];
                    geo.vertices.push(new THREE.Vector3(v.x, v.y, v.z));
                }

                for(var i=0; i < shape.faces.length; i++){
                    var face = shape.faces[i];

                    // add triangles
                    var a = face[0];
                    for (var j = 1; j < face.length - 1; j++) {
                        var b = face[j];
                        var c = face[j + 1];
                        geo.faces.push(new THREE.Face3(a, b, c));
                    }
                }
                geo.computeBoundingSphere();
                geo.computeFaceNormals();
                mesh = new THREE.Mesh( geo, color_mat );
                break;

            case CANNON.Shape.types.HEIGHTFIELD:
                var geometry = new THREE.Geometry();

                var v0 = new CANNON.Vec3();
                var v1 = new CANNON.Vec3();
                var v2 = new CANNON.Vec3();
                for (var xi = 0; xi < shape.data.length - 1; xi++) {
                    for (var yi = 0; yi < shape.data[xi].length - 1; yi++) {
                        for (var k = 0; k < 2; k++) {
                            shape.getConvexTrianglePillar(xi, yi, k===0);
                            v0.copy(shape.pillarConvex.vertices[0]);
                            v1.copy(shape.pillarConvex.vertices[1]);
                            v2.copy(shape.pillarConvex.vertices[2]);
                            v0.vadd(shape.pillarOffset, v0);
                            v1.vadd(shape.pillarOffset, v1);
                            v2.vadd(shape.pillarOffset, v2);
                            geometry.vertices.push(
                                new THREE.Vector3(v0.x, v0.y, v0.z),
                                new THREE.Vector3(v1.x, v1.y, v1.z),
                                new THREE.Vector3(v2.x, v2.y, v2.z)
                            );
                            var i = geometry.vertices.length - 3;
                            geometry.faces.push(new THREE.Face3(i, i+1, i+2));
                        }
                    }
                }
                geometry.computeBoundingSphere();
                geometry.computeFaceNormals();
                mesh = new THREE.Mesh(geometry, color_mat);
                break;

            case CANNON.Shape.types.TRIMESH:
                var geometry = new THREE.Geometry();

                var v0 = new CANNON.Vec3();
                var v1 = new CANNON.Vec3();
                var v2 = new CANNON.Vec3();
                for (var i = 0; i < shape.indices.length / 3; i++) {
                    shape.getTriangleVertices(i, v0, v1, v2);
                    geometry.vertices.push(
                        new THREE.Vector3(v0.x, v0.y, v0.z),
                        new THREE.Vector3(v1.x, v1.y, v1.z),
                        new THREE.Vector3(v2.x, v2.y, v2.z)
                    );
                    var j = geometry.vertices.length - 3;
                    geometry.faces.push(new THREE.Face3(j, j+1, j+2));
                }
                geometry.computeBoundingSphere();
                geometry.computeFaceNormals();
                mesh = new THREE.Mesh(geometry, color_mat);
                break;

            default:
                throw "Visual type not recognized: "+shape.type;
            }

            // mesh.receiveShadow = true;
            // mesh.castShadow = true;
            // if(mesh.children){
            //     for(var i=0; i<mesh.children.length; i++){
            //         mesh.children[i].castShadow = true;
            //         mesh.children[i].receiveShadow = true;
            //         if(mesh.children[i]){
            //             for(var j=0; j<mesh.children[i].length; j++){
            //                 mesh.children[i].children[j].castShadow = true;
            //                 mesh.children[i].children[j].receiveShadow = true;
            //             }
            //         }
            //     }
            // }

            var o = _body.shapeOffsets[l];
            var q = _body.shapeOrientations[l];
            mesh.position.set(o.x, o.y, o.z);
            mesh.quaternion.set(q.x, q.y, q.z, q.w);

            obj.add(mesh);
        }

        obj.cannon_rigid_body = _body
        this.threejs.scene.add( obj )
    }


    render( _sec )
    {
        this.cannon_world.step( _sec )
        this.threejs.render()
    }
}

// MAIN
let cannon_phy = new CANNON_PHYSICS( new THREEJS() )

cannon_phy.add_box( {
    mass: 0, x: 0, y: -0.2, z: 0, w: 150, h: 0.4, d: 150, color: 0x333333,
} )

// ドミノを作って、倒してみる。

const dataSet = [
    0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,
    0,0,0,0,0,0,3,3,3,3,3,0,0,1,1,1,
    0,0,0,0,0,3,3,3,3,3,3,3,3,3,1,1,
    0,0,0,0,0,2,2,2,1,1,2,1,0,3,3,3,
    0,0,0,0,2,1,2,1,1,1,2,1,1,3,3,3,
    0,0,0,0,2,1,2,2,1,1,1,2,1,1,1,3,
    0,0,0,0,2,2,1,1,1,1,2,2,2,2,3,0,
    0,0,0,0,0,0,1,1,1,1,1,1,1,3,0,0,
    0,0,3,3,3,3,3,5,3,3,3,5,3,0,0,0,
    0,3,3,3,3,3,3,3,5,3,3,3,5,0,0,2,
    1,1,3,3,3,3,3,3,5,5,5,5,5,0,0,2,
    1,1,1,0,5,5,3,5,5,4,5,5,4,5,2,2,
    0,1,0,2,5,5,5,5,5,5,5,5,5,5,2,2,
    0,0,2,2,2,5,5,5,5,5,5,5,5,5,2,2,
    0,2,2,2,5,5,5,5,5,5,5,0,0,0,0,0,
    0,2,0,0,5,5,5,5,0,0,0,0,0,0,0,0
]

const box_size = 1.5
for ( let y=0 ; y<16; y++ ) {
    for ( let x=0 ; x<16; x++ ) {
        cannon_phy.add_box( {
            mass: 1,
            x: (x-7) * box_size * 0.95, y: box_size * 0.5, z: (y-7) * box_size * 1.2,
            w: box_size*0.1, h: box_size*1, d: box_size*1,
            color: [ 0xDCAA6B, 0xffcccc, 0x800000, 0xff0000, 0xffff00, 0x0000ff ][ dataSet[ y * 16 + x ] ],
        })
    }
}

for ( let i=0 ; i<16; i++ ) {
    cannon_phy.add_box({
        mass: 3,
        x: -7 * box_size, y: box_size * 3, z: (i-7) * box_size * 1.2,
        w: box_size, h: box_size, d: box_size,
        color: 0xeeeeee
    })
}





// 前輪駆動のくるまっぽい物体を作って、落とす。

var w_mat           = new CANNON.Material()
// var ws              = new CANNON.Sphere( 2.0 )
var ws              = new CANNON.Cylinder( 1.9, 1.2, 1, 5 ) // radiusTop  radiusBottom  height  numSegments

var leftFrontWheel  = new CANNON.Body({ mass: 1, material: w_mat, shape: ws, position: { x: 5, y:  5+20, z: 0 }, quaternion: new CANNON.Quaternion( 1, 0, 0, -Math.PI / 4 ) } ) // Quaternionで向きを決めているが、最終的には、HingeConstraintの axisB で補正される。
var rightFrontWheel = new CANNON.Body({ mass: 1, material: w_mat, shape: ws, position: { x: 5, y: -5+20, z: 0 }, quaternion: new CANNON.Quaternion( 1, 0, 0,  Math.PI / 4 ) } )
var leftRearWheel   = new CANNON.Body({ mass: 1, material: w_mat, shape: ws, position: { x:-5, y:  5+20, z: 0 }, quaternion: new CANNON.Quaternion( 1, 0, 0, -Math.PI / 4 ) } )
var rightRearWheel  = new CANNON.Body({ mass: 1, material: w_mat, shape: ws, position: { x:-5, y: -5+20, z: 0 }, quaternion: new CANNON.Quaternion( 1, 0, 0,  Math.PI / 4 ) } )

// Hinge the wheels
var chassis = new CANNON.Body({
    mass: 5,
    shape: new CANNON.Box( new CANNON.Vec3( 5, 2, 0.5 ) ),
    position: { x: 0, y: 20, z: 0 }
})

// Constrain wheels
var constraints = []
// Position constrain wheels
var zero = new CANNON.Vec3()
constraints.push( new CANNON.HingeConstraint( chassis, leftFrontWheel,  { pivotA: new CANNON.Vec3(  5,  5, 0 ), axisA: new CANNON.Vec3( 1, 1, 0 ), pivotB: zero, axisB: new CANNON.Vec3( 0, 0, -1, ) } ) )
constraints.push( new CANNON.HingeConstraint( chassis, rightFrontWheel, { pivotA: new CANNON.Vec3(  5, -5, 0 ), axisA: new CANNON.Vec3( 1, 1, 0 ), pivotB: zero, axisB: new CANNON.Vec3( 0, 0, -1, ) } ) )
constraints.push( new CANNON.HingeConstraint( chassis, leftRearWheel,   { pivotA: new CANNON.Vec3( -5,  5, 0 ), axisA: new CANNON.Vec3( 0, 1, 0 ), pivotB: zero, axisB: new CANNON.Vec3( 0, 0, -1, ) } ) )
constraints.push( new CANNON.HingeConstraint( chassis, rightRearWheel,  { pivotA: new CANNON.Vec3( -5, -5, 0 ), axisA: new CANNON.Vec3( 0, 1, 0 ), pivotB: zero, axisB: new CANNON.Vec3( 0, 0, -1, ) } ) )

for(var i=0; i<constraints.length; i++)
    cannon_phy.cannon_world.addConstraint( constraints[i] )

for ( const body of [ chassis, leftFrontWheel, rightFrontWheel, leftRearWheel, rightRearWheel ] )
{
    cannon_phy.add_body( body, 0x556677 )
}

// Enable motors and set their velocities
var frontLeftHinge  = constraints[0];
var frontRightHinge = constraints[1];
frontLeftHinge.enableMotor()
frontRightHinge.enableMotor()
var v = 7
frontLeftHinge.setMotorSpeed( v )
frontRightHinge.setMotorSpeed( -v )


function animate()
{
    cannon_phy.render( 1 / 60 )
    window.requestAnimationFrame( animate )
}
window.requestAnimationFrame( animate )

</script>
</body>
</html>
            
          
!
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