EzDevInfo.com

Physijs

Physics plugin for Three.js

Sphere inside of a sphere threejs physijs

I'm trying to make a sort of "lottery ball" simulator.

I'm having difficulty adding an object inside an object with physijis.

Physics work when I add the sphere to the scene, but when I add the child spheres to the main "lottery" sphere, it loses the physics.

If anyone could help, that would be great.

Thanks


Source: (StackOverflow)

PhysiJS do not work on localhost (works fine on online examples)

As can be seen in the title, when I run the example of physiJS (from github repo) it show only background, fps counter, but no physiJS functionality at all (pure three.js works fine). When I run on the: http://chandlerprall.github.io/Physijs/examples/vehicle.html everything runs ok. I have no idea right now where to start looking and where the problem is. Any ideas of what the cause could be?


Source: (StackOverflow)

Advertisements

FPS Demo Physi.js - Player sinking through floor

I am working on a FPS demo using three.js and physi.js (ammo physics) and I have a problem I can't solve. When I start the simulation and the player has not moved everything is good. When I move the player in any direction or jump, the player's mesh begins to fall through the floor (y-axis). The mesh is a Physijs.CapsuleMesh and the floor is a Physijs.BoxMesh. Can someone help me figure this out?

A url to the demo is below. The 2 important files are 'Player.js' and 'main.js'.

FPS Simulation


Source: (StackOverflow)

Physijs - ConvexMesh wall collision detection issue

I'm using Three.js and Physijs. I have a wall that should act as a boundary, but objects (especially boxes) often pass through it, if the force is sufficient. The collision is detected, as they do not do so cleanly, but they start spinning or bounce in some direction. Is there a way to increase the maximum force with which the wall can act on the colliding object?

All four of the wall's points are on the same plane, forming a rectangle. The mesh consists of two large triangular faces. I'm using a ConvexMesh.

Breaking the two triangles into many smaller ones does not alleviate the problem.

I can confirm the normals are fine, as the wall is shaded correctly.

How can I solve this without converting the wall into a BoxMesh?

I'll also appreciate an explanation of why this happens. I'm guessing that the engine limits the maximum force that collisions can apply.


Source: (StackOverflow)

add physics on blender model, three.js Physijs

How can i add physics on a blender model ? I tried ConvexMesh, ConcaveMesh but no luck.

var mesh = {... blender exporter ...}

var loader = new THREE.JSONLoader();
var mesh_obj = loader.parse(mesh,'./');
var mesh_materials = mesh_obj.materials;
var mesh_geometry = mesh_obj.geometry;

var _materials=[];
for ( var i = 0, i<mesh_materials.length;i ++ ) {
 var materialv = Physijs.createMaterial(mesh_materials[i],0.8,0.1);
 _materials.push(materialv)
}

mesh = new Physijs.ConcaveMesh(mesh_geometry, new THREE.MeshFaceMaterial(_materials),0 );
scene.add(mesh)

screenshoot


Source: (StackOverflow)

Threejs/Physijs Game MMO Character controlls

I'm working on a third person character control for a game i'm developing. I'm happy with the results so far. The character controls have a lot of neat features like: if an object is in front of the camera it will move forward so you can still see the character, however the camera stutters horribly when I rotate it to the side and then turn my player away from it. I uploaded a test on JSFiddle: http://jsfiddle.net/nA8SV/ I have only tested this in chrome, and for some reason the results part doesn't get the keypresses until you click on the white space bordering the canvas on that frame.

[also i started chrome with "--disable-web-security" to ignore the cross origin]

But once you click the page the key presses work. The controls are a modified version of the orbital controls. So you can left click and rotate the view. Additionally you can use the wasd keys to move around and the camera view should return behind the player when you are moving/rotating.

I apologize for the buggyness this was very difficult to get working on JSFiddle. (But the rotation bug is happening so it at least reproduces that.)

Basically I'm trying to get my camera rotation back behind my character, so i have some code that fixes the rotation on line 250, but the camera stutters as the character moves.

Here are my theories I think the camera overall jerkyness has something to do with the physics simulation bouncing the player around slightly, but I'm not sure what to do to solve this, any help would be appreciated.

here is the code for completeness but I would recommend the JSFiddle link, I'ts much easier to see it work.

THREE.PlayerControls = function (anchor, scene, player, camera, domElement) {

this.walking = false;
this.occ = false;
this.scene = scene;
this.occLastZoom = 0;
this.jumpRelease = true;
this.jumping = false;
this.falling = false;
this.moving = false;
this.turning = false;
this.anchor = anchor;
this.player = player;
this.camera = camera;
this.camera.position.set(0, 8.25, -20);
this.domElement = (domElement !== undefined) ? domElement : document;

this.anchor.add(this.camera);

// API
this.enabled = true;

this.center = new THREE.Vector3(0, 4, 0);

this.userZoom = true;
this.userZoomSpeed = 2.0;

this.userRotate = true;
this.userRotateSpeed = 1.0;

this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians

this.minDistance = 2;
this.maxDistance = 30;

this.keys = {
    LEFT: 65,
    STRAFFLEFT: 81,
    UP: 87,
    RIGHT: 68,
    STRAFFRIGHT: 69,
    DOWN: 83,
    JUMP: 32,
    SLASH: 191
};

// internals
var scope = this;

var EPS = 0.000001;
var PIXELS_PER_ROUND = 1800;

var rotateStart = new THREE.Vector2();
var rotateEnd = new THREE.Vector2();
var rotateDelta = new THREE.Vector2();

var zoomStart = new THREE.Vector2();
var zoomEnd = new THREE.Vector2();
var zoomDelta = new THREE.Vector2();

var phiDelta = 0;
var thetaDelta = 0;
var scale = 1;

var lastPosition = new THREE.Vector3();

var STATE = {
    NONE: -1,
    ROTATE: 0,
    ZOOM: 1
};
var state = STATE.NONE;
var key_state = [];

// events
var changeEvent = {
    type: 'change'
};


this.rotateLeft = function (angle) {
    thetaDelta -= angle;
};

this.rotateRight = function (angle) {
    thetaDelta += angle;
};

this.rotateUp = function (angle) {
    phiDelta -= angle;
};

this.rotateDown = function (angle) {
    phiDelta += angle;
};

this.zoomIn = function (zoomScale) {
    if (zoomScale === undefined) {
        zoomScale = getZoomScale();
    }
    scale /= zoomScale;
};

this.zoomOut = function (zoomScale) {
    if (zoomScale === undefined) {
        zoomScale = getZoomScale();
    }
    scale *= zoomScale;
};

this.update = function (delta) {
    // detect falling
    if (this.scene.children.length > 0) {
        var originPoint = this.anchor.position.clone();
        var ray = new THREE.Raycaster(originPoint, new THREE.Vector3(0, -1, 0));
        var collisionResults = ray.intersectObjects(this.scene.children.filter(function (child) {
            return child.occ;
        }));
        if (collisionResults.length > 0) {
            if (collisionResults[0].distance < 1.25 && this.falling) {
                this.falling = false;
                this.jumping = false;
            } else if (collisionResults[0].distance > 2 + (this.jumping ? 1 : 0) && !this.falling) {
                this.falling = true;
            }
        }
    }

    // handle movement
    if (!this.falling) {
        if (key_state.indexOf(this.keys.JUMP) > -1 && this.jumpRelease && !this.jumping) {
            // jump
            var lv = this.anchor.getLinearVelocity();
            this.anchor.setLinearVelocity(new THREE.Vector3(lv.x, 15, lv.z));
            this.jumpRelease = false;
            this.jumping = true;
            //jump
        } else if (!this.jumping) {
            // move
            if (key_state.indexOf(this.keys.UP) > -1) {

                var rotation_matrix = new THREE.Matrix4().extractRotation(this.anchor.matrix);

                var speed = this.walking ? 2.5 : 10;
                var force_vector;

                // straffing?
                if (key_state.indexOf(this.keys.STRAFFLEFT) > -1 && key_state.indexOf(this.keys.STRAFFRIGHT) < 0) {
                    force_vector = new THREE.Vector3((2 * speed / 3), 0, (2 * speed / 3)).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, Math.PI / 4, 0);
                } else if (key_state.indexOf(this.keys.STRAFFRIGHT) > -1) {
                    force_vector = new THREE.Vector3((-2 * speed / 3), 0, (2 * speed / 3)).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, -Math.PI / 4, 0);
                } else {
                    force_vector = new THREE.Vector3(0, 0, speed).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, 0, 0);
                }

                this.anchor.setLinearVelocity(force_vector);
                this.moving = true;

                // forward
            } else if (key_state.indexOf(this.keys.DOWN) > -1) {
                var rotation_matrix = new THREE.Matrix4().extractRotation(this.anchor.matrix);

                var speed = this.walking ? -2.5 : -5;
                var force_vector;

                // straffing?
                if (key_state.indexOf(this.keys.STRAFFLEFT) > -1 && key_state.indexOf(this.keys.STRAFFRIGHT) < 0) {
                    force_vector = new THREE.Vector3((-2 * speed / 3), 0, (2 * speed / 3)).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, -Math.PI / 4, 0);
                } else if (key_state.indexOf(this.keys.STRAFFRIGHT) > -1) {
                    force_vector = new THREE.Vector3((2 * speed / 3), 0, (2 * speed / 3)).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, Math.PI / 4, 0);
                } else {
                    force_vector = new THREE.Vector3(0, 0, speed).applyMatrix4(rotation_matrix);
                    this.player.rotation.set(0, 0, 0);
                }

                this.anchor.setLinearVelocity(force_vector);
                this.moving = true;

                //back
            } else if (key_state.indexOf(this.keys.STRAFFLEFT) > -1) {
                var rotation_matrix = new THREE.Matrix4().extractRotation(this.anchor.matrix);

                var speed = this.walking ? 2.5 : 10;
                var force_vector = new THREE.Vector3(speed, 0, 0).applyMatrix4(rotation_matrix);
                this.player.rotation.set(0, Math.PI / 2, 0);

                this.anchor.setLinearVelocity(force_vector);
                this.moving = true;

                //straff
            } else if (key_state.indexOf(this.keys.STRAFFRIGHT) > -1) {
                var rotation_matrix = new THREE.Matrix4().extractRotation(this.anchor.matrix);

                var speed = this.walking ? 2.5 : 10;
                var force_vector = new THREE.Vector3(-speed, 0, 0).applyMatrix4(rotation_matrix);
                this.player.rotation.set(0, -Math.PI / 2, 0);

                this.anchor.setLinearVelocity(force_vector);
                this.moving = true;

                //straff
            } else if (this.moving) {
                this.player.rotation.set(0, 0, 0);
                this.anchor.setLinearVelocity(new THREE.Vector3(0, 0, 0));
                this.moving = false;
            }

            //turn
            if (key_state.indexOf(this.keys.LEFT) > -1 && key_state.indexOf(this.keys.RIGHT) < 0) {
                this.anchor.setAngularVelocity(new THREE.Vector3(0, 1.5, 0));
                this.turning = true;
                //turning
            } else if (key_state.indexOf(this.keys.RIGHT) > -1) {
                this.anchor.setAngularVelocity(new THREE.Vector3(0, -1.5, 0));
                this.turning = true;
                //turning
            } else if (this.turning) {
                this.anchor.setAngularVelocity(new THREE.Vector3(0, 0, 0));
                this.turning = false;
            }

            //idle
        }

        if (key_state.indexOf(this.keys.JUMP) == -1) {
            this.jumpRelease = true;
        }
    } else {
        //falling
    }

    var position = this.camera.position;
    var offset = position.clone().sub(this.center);

    // angle from z-axis around y-axis
    var theta = Math.atan2(offset.x, offset.z);

    // angle from y-axis
    var phi = Math.atan2(Math.sqrt(offset.x * offset.x + offset.z * offset.z), offset.y);

    theta += thetaDelta;
    phi += phiDelta;

    if ((this.moving || this.turning) && state != STATE.ROTATE) {
        // fix camera rotation
        if (theta < 0) theta -= Math.max(delta, (-1 * Math.PI) + theta);
        else theta += Math.min(delta, Math.PI - theta);

        // fix pitch (should be an option or it could get anoying)
        //phi = 9*Math.PI/24;
    }

    // restrict phi to be between desired limits
    phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, phi));

    // restrict phi to be betwee EPS and PI-EPS
    phi = Math.max(EPS, Math.min(Math.PI - EPS, phi));

    var radius;
    if (this.occ) {
        this.occLastZoom = Math.max(this.minDistance, Math.min(this.maxDistance, this.occLastZoom * scale));
        radius = this.occLastZoom;
    } else {
        radius = offset.length() * scale;
    }

    // restrict radius to be between desired limits
    radius = Math.max(this.minDistance, Math.min(this.maxDistance, radius));

    // check for objects infront of camera
    var projector = new THREE.Projector();
    var vector = new THREE.Vector3(0, 0, 1);
    projector.unprojectVector(vector, camera);
    var point = new THREE.Vector3(this.anchor.position.x + this.center.x, this.anchor.position.y + this.center.y, this.anchor.position.z + this.center.z);
    var vec = camera.position.clone().sub(vector).normalize()

    var checkray = new THREE.Raycaster(point, vec, this.minDistance, this.maxDistance);
    var checkcollisionResults = checkray.intersectObjects(this.scene.children.filter(function (child) {
        return child.occ;
    }));
    if (checkcollisionResults.length > 0) {
        var min = radius;
        for (var i = 0; i < checkcollisionResults.length; i++) {
            if (min > checkcollisionResults[i].distance) min = checkcollisionResults[i].distance;
        }
        if (min < radius) {
            if (!this.occ) {
                this.occ = true;
                this.occLastZoom = radius;
            }
            radius = min;
        } else {
            this.occ = false;
        }
    }

    offset.x = radius * Math.sin(phi) * Math.sin(theta);
    offset.y = radius * Math.cos(phi);
    offset.z = radius * Math.sin(phi) * Math.cos(theta);

    if (radius < 5) {
        this.player.material.opacity = Math.max(0, radius / 5.0);
        this.center.y = 4 + ((5 - radius) / 2.5);
    } else {
        if (this.player.material.opacity != 1.0) {
            this.player.material.opacity = 1.0;
            this.center.y = 4;
        }
    }

    position.copy(this.center).add(offset);
    this.camera.lookAt(this.center);

    thetaDelta = 0;
    phiDelta = 0;
    scale = 1;

    if (lastPosition.distanceTo(this.camera.position) > 0) {
        this.dispatchEvent(changeEvent);
        lastPosition.copy(this.camera.position);
    }
};

function roundTothree(num) {
    return +(Math.round(num + "e+3") + "e-3");
}

function getZoomScale() {
    return Math.pow(0.95, scope.userZoomSpeed);
}

function onMouseDown(event) {
    if (scope.enabled === false) return;
    if (scope.userRotate === false) return;

    event.preventDefault();

    if (state === STATE.NONE) {
        if (event.button === 0) state = STATE.ROTATE;
    }

    if (state === STATE.ROTATE) {
        rotateStart.set(event.clientX, event.clientY);
    }

    document.addEventListener('mousemove', onMouseMove, false);
    document.addEventListener('mouseup', onMouseUp, false);
}

function onMouseMove(event) {
    if (scope.enabled === false) return;
    event.preventDefault();

    if (state === STATE.ROTATE) {
        rotateEnd.set(event.clientX, event.clientY);
        rotateDelta.subVectors(rotateEnd, rotateStart);
        scope.rotateLeft(2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed);
        scope.rotateUp(2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed);
        rotateStart.copy(rotateEnd);
    } else if (state === STATE.ZOOM) {
        zoomEnd.set(event.clientX, event.clientY);
        zoomDelta.subVectors(zoomEnd, zoomStart);
        if (zoomDelta.y > 0) {
            scope.zoomIn();
        } else {
            scope.zoomOut();
        }
        zoomStart.copy(zoomEnd);
    }
}

function onMouseUp(event) {
    if (scope.enabled === false) return;
    if (scope.userRotate === false) return;

    document.removeEventListener('mousemove', onMouseMove, false);
    document.removeEventListener('mouseup', onMouseUp, false);

    state = STATE.NONE;
}

function onMouseWheel(event) {
    if (scope.enabled === false) return;
    if (scope.userZoom === false) return;

    var delta = 0;

    if (event.wheelDelta) { // WebKit / Opera / Explorer 9
        delta = event.wheelDelta;
    } else if (event.detail) { // Firefox
        delta = -event.detail;
    }

    if (delta > 0) {
        scope.zoomOut();
    } else {
        scope.zoomIn();
    }
}

function onKeyDown(event) {
    console.log('onKeyDown')
    if (scope.enabled === false) return;
    switch (event.keyCode) {
        case scope.keys.UP:
            var index = key_state.indexOf(scope.keys.UP);
            if (index == -1) key_state.push(scope.keys.UP);
            break;
        case scope.keys.DOWN:
            var index = key_state.indexOf(scope.keys.DOWN);
            if (index == -1) key_state.push(scope.keys.DOWN);
            break;
        case scope.keys.LEFT:
            var index = key_state.indexOf(scope.keys.LEFT);
            if (index == -1) key_state.push(scope.keys.LEFT);
            break;
        case scope.keys.STRAFFLEFT:
            var index = key_state.indexOf(scope.keys.STRAFFLEFT);
            if (index == -1) key_state.push(scope.keys.STRAFFLEFT);
            break;
        case scope.keys.RIGHT:
            var index = key_state.indexOf(scope.keys.RIGHT);
            if (index == -1) key_state.push(scope.keys.RIGHT);
            break;
        case scope.keys.STRAFFRIGHT:
            var index = key_state.indexOf(scope.keys.STRAFFRIGHT);
            if (index == -1) key_state.push(scope.keys.STRAFFRIGHT);
            break;
        case scope.keys.JUMP:
            var index = key_state.indexOf(scope.keys.JUMP);
            if (index == -1) key_state.push(scope.keys.JUMP);
            break;
    }
}

function onKeyUp(event) {
    switch (event.keyCode) {
        case scope.keys.UP:
            var index = key_state.indexOf(scope.keys.UP);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.DOWN:
            var index = key_state.indexOf(scope.keys.DOWN);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.LEFT:
            var index = key_state.indexOf(scope.keys.LEFT);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.STRAFFLEFT:
            var index = key_state.indexOf(scope.keys.STRAFFLEFT);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.RIGHT:
            var index = key_state.indexOf(scope.keys.RIGHT);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.STRAFFRIGHT:
            var index = key_state.indexOf(scope.keys.STRAFFRIGHT);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.JUMP:
            var index = key_state.indexOf(scope.keys.JUMP);
            if (index > -1) key_state.splice(index, 1);
            break;
        case scope.keys.SLASH:
            scope.walking = !scope.walking;
            break;

    }
}

this.domElement.addEventListener('contextmenu', function (event) {
    event.preventDefault();
}, false);
this.domElement.addEventListener('mousedown', onMouseDown, false);
this.domElement.addEventListener('mousewheel', onMouseWheel, false);
this.domElement.addEventListener('DOMMouseScroll', onMouseWheel, false); // firefox
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
};

THREE.PlayerControls.prototype = Object.create(THREE.EventDispatcher.prototype);


// end player controlls
Physijs.scripts.worker = 'https://rawgithub.com/chandlerprall/Physijs/master/physijs_worker.js';
Physijs.scripts.ammo = 'http://chandlerprall.github.io/Physijs/examples/js/ammo.js';

// standard global variables
var container, scene, camera, renderer, controls;
//var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();

// MAIN //
window.onload = function() {
console.log('loaded')

// SCENE //
scene = new Physijs.Scene();
scene.setGravity(new THREE.Vector3(0, -32, 0));
scene.addEventListener(
    'update',

function () {
    scene.simulate();
});

// CAMERA //
var SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
    ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT,
    NEAR = 1,
    FAR = 1000;
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);

// RENDERER //
renderer = new THREE.WebGLRenderer({
    antialias: true
});
renderer.shadowMapEnabled = true;
// to antialias the shadow
renderer.shadowMapSoft = true;

renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);

container = document.getElementById('container');
container.appendChild(renderer.domElement);

// EVENTS //
//THREEx.WindowResize(renderer, camera);

// LIGHT //
var hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
hemiLight.color.setHSL(0.6, 1, 0.6);
hemiLight.groundColor.setHSL(0.095, 1, 0.75);
hemiLight.position.set(0, 500, 0);
scene.add(hemiLight);

var light = new THREE.DirectionalLight(0xffffff, 1);
light.color.setHSL(0.1, 1, 0.95);
light.position.set(-1, 1.75, 1);
light.position.multiplyScalar(50);
light.castShadow = true;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
light.shadowDarkness = 0.5;
var d = 50;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowCameraFar = 3500;
light.shadowBias = -0.0001;
light.shadowDarkness = 0.35;
scene.add(light);

// GEOMETRY //
var checkerboard = new THREE.ImageUtils.loadTexture('http://www.cns.nyu.edu/lcv/texture/artificial-periodic/checkerboard.o.jpg');
checkerboard.wrapS = checkerboard.wrapT = THREE.RepeatWrapping;
checkerboard.repeat.set(4, 4);

var checkerboard2 = new THREE.ImageUtils.loadTexture('http://www.cns.nyu.edu/lcv/texture/artificial-periodic/checkerboard.o.jpg');

var cubeMaterial = Physijs.createMaterial(
new THREE.MeshLambertMaterial({
    map: checkerboard2
}),
1.0, // high friction
0.0 // low restitution
);
var cubeGeometry = new THREE.CubeGeometry(10, 5, 10, 1, 1, 1);
var cube = new Physijs.BoxMesh(
cubeGeometry,
cubeMaterial,
1);

cube.position.set(-10, 1, -10);
cube.castShadow = true;
cube.receiveShadow = true;
cube.occ = true;
scene.add(cube);


var cubeMaterial2 = Physijs.createMaterial(
new THREE.MeshLambertMaterial({
    map: checkerboard2
}),
1.0, // high friction
0.0 // low restitution
);
var cubeGeometry2 = new THREE.CubeGeometry(10, 5, 10, 1, 1, 1);
var cube2 = new Physijs.BoxMesh(
cubeGeometry2,
cubeMaterial2,
1);

cube2.position.set(-10, 7, -1);
cube2.castShadow = true;
cube2.receiveShadow = true;
cube2.occ = true;
scene.add(cube2);

var cubeMaterial3 = Physijs.createMaterial(
new THREE.MeshLambertMaterial({
    map: checkerboard2
}),
1.0, // high friction
0.0 // low restitution
);
var cubeGeometry3 = new THREE.CubeGeometry(10, 5, 10, 1, 1, 1);
var cube3 = new Physijs.BoxMesh(
cubeGeometry3,
cubeMaterial3,
1);

cube3.position.set(-10, 13, 8);
cube3.castShadow = true;
cube3.receiveShadow = true;
cube3.occ = true;
scene.add(cube3);

var cone = new Physijs.ConeMesh(
new THREE.CylinderGeometry(0, 5, 4, 30, 30, true),
Physijs.createMaterial(
new THREE.MeshLambertMaterial({
    map: checkerboard2
}),
1.0, // high friction
0.0 // low restitution
),
0);
cone.position.set(0, 2, 0);
scene.castShadow = true;
scene.receiveShadow = true;
cone.occ = true;
scene.add(cone);


// FLOOR //
var floorMaterial = new THREE.MeshLambertMaterial({
    map: checkerboard
});
var floorGeometry = new THREE.PlaneGeometry(100, 100, 1, 1);
var floor = new Physijs.PlaneMesh(floorGeometry, floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.castShadow = false;
floor.receiveShadow = true;
floor.occ = true;
scene.add(floor);

// SKY //
var skyBoxGeometry = new THREE.CubeGeometry( 1000, 1000, 1000 );
var skyBox = new THREE.Mesh(skyBoxGeometry, new THREE.MeshLambertMaterial({
    color: '#3333bb'
}));
scene.add(skyBox);

// fog must be added to scene before first render
scene.fog = new THREE.FogExp2(0x999999, 0.001);


var bounding = new Physijs.SphereMesh(
new THREE.SphereGeometry(0.75, 4, 4),
Physijs.createMaterial(
new THREE.MeshBasicMaterial({
    color: '#ff0000'
}),
1.0, // high friction
0.0 // low restitution
),
0.1);

var player = new THREE.Mesh(
new THREE.CubeGeometry(1, 6, 1, 1, 1, 1),
new THREE.MeshLambertMaterial({
    color: '#00ff00'
}),
1);
player.position.set(0, 3, 0);

bounding.position.set(10, 0.75, -10);
bounding.add(player);

scene.add(bounding);
bounding.setAngularFactor(new THREE.Vector3(0, 0, 0));
controls = new THREE.PlayerControls(bounding, scene, player, camera, renderer.domElement);

// animation loop / game loop
scene.simulate();
animate();
};

function animate() {
requestAnimationFrame(animate);
render();
update();
}

function update() {
// delta = change in time since last call (in seconds)
var delta = clock.getDelta();
THREE.AnimationHandler.update(delta);
if (controls) controls.update(delta);
}

function render() {
    renderer.render(scene, camera);
}

Thank you!!!


Source: (StackOverflow)

How to turn off Physijs to improve performance on mobile devices?

I'm trying to find a way to improve performance of my card game on mobile devices (wrapped with Cordova).

The script detect if WebGL is available and fallback to Canvas 2d if it's not supported. But I get a low 5-10fps on my Samsung Galaxy S4.

Is it possible to turn off Physijs? If not, how can I rewrite Physijs functions to only return ThreeJS objects instead of Physijs objects? Exmeple:

if(disablePhysics) {
        Physijs.createMaterial(elem,v1,v2) {
            return elem;
        }
    }

your help, as always, is valuable, thank you :)


Source: (StackOverflow)

Physijs stops updating?

I'm trying to make a small project using Three.js & the physics plugin physijs; just a little dice roller. My approach is to use setGravity to move the dice around, modelling gravity to move the dice around. The issue I'm running into is that once the dice come to a rest, they no longer respond to gravity. Has anyone run into this before?


Source: (StackOverflow)

Physijs, combining movement and physics

I've been looking around for a while now for a conclusion for this, but I seem to be unable to find any solution to this.

I'm trying to create a simple scene to get a little platform action to work using THREE.JS and PHYSI.JS. I have one flat box with a mass of 0 to act as my workd, and a box mesh to act as my character. The site of Physijs appears to suggest that I set the __dirtyPosition variable to true. The problem here is this: __dirtyPosition messes with the physics. As I move my character off the edge of the level, he's not falling. In fact, it seems to stop halfway the world cube when it does collide.

When I try to update the position without applying __dirtyPosition, the cube gets put back in it's place. It trembles a bit as if it's having a tiny seizure and that's it. It'd be great if I could use both physics and movement, using Physi for just collision feels kind of like overdoing it. Here's how I do it now, clearly the wrong way:

level1.generateScene = function()
{
   level1.camera = new THREE.PerspectiveCamera(75, this.cameraWidth / this.cameraHeight, 0.1, 1000);

   level1.material = new AdapterEngine.createBasicMaterial({color: 0x00ff00}); //Threejs basic material
   level1.ground = new AdapterEngine.createBoxMesh(5, 0.1, 5, level1.material, 0); //Physijs box mesh with a mass of 0

   level1.playerMaterial = new AdapterEngine.createBasicMaterial({color:0x0000ff}, 0.6, 0.3); //Physijs basic material with a fruction of 0.6, and a restitution of 0.3
   level1.player = new AdapterEngine.createBoxMesh(0.3, 0.3, 0.3, level1.playerMaterial, 0.1); //Physijs box mesh with a mass of 0.1
   level1.player.y = 50; //yes, it should fall down for a bit.

   level1.scene.add(level1.ground);
   level1.scene.add(level1.player);

   level1.camera.position.z = 5;
   level1.camera.position.y = 1.4;
   level1.activeCamera = level1.camera;
   level1.controls.init();
}

This is the function where the 'level', with both character and world gets created. What the level object also contains, is an update function that plays when after the requestAnimationframe function is called, and right before the renderer renders.

level1.update = function()
{
   this.scene.simulate();

   level1.player.__dirtyPosition = true;
   if(level1.controls.isKeyDown('RIGHT')) level1.xvelocity = 0.1;
   else if(level1.controls.isKeyDown('LEFT')) level1.xvelocity = -0.1;
   else if(level1.controls.isKeyUp('RIGHT') || level1.controls.isKeyUp('LEFT')) level1.xvelocity = 0;

   level1.player.rotation.x = 0;
   level1.player.rotation.y = 0;
   level1.player.rotation.z = 0;

   level1.player.position.x = level1.player.position.x + 0.5*level1.xvelocity;
}

I know similar questions have popped up, but none have really yielded satisfactory answers. I am genuinely at a loss of what to do, or which functions I should use.

edit I forgot to add this part: I've been using a little framework that determines whether I should get a THREE.js object or a PHYSI.js object that works as a bridge between my game and my libraries. These follow the same parameters as THREE.js and PHYSI.js do, I have marked with comments which function returns which type of object.


Source: (StackOverflow)

Physijs object goes through concaveMesh

I've a problem that seems to be known: my "bounding" object doesn't collide with "floor" concaveMesh.

I already read that this issue could be caused by an error in scaling concaveMesh together with the model, so I exported my floor model scaled as I need it and after I applied a concaveMesh (as follow) but it doesn't work.

I red this: https://github.com/chandlerprall/Physijs/issues/102 and a lot of other things about this topic (Physijs Load model three.js collisions don't work and a similar) and I made the following code but nothing to do :(

I really don't understand why "bounding" goes through the floor.

Here my code:

Physijs.scripts.worker = './libs/chandlerprall-Physijs-7e3837b/physijs_worker.js';
Physijs.scripts.ammo = './examples/js/ammo.js';
var gravityVector = new THREE.Vector3( 0, -100, 0 );
//renderer
var renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setClearColor(0xffffff, 0);
renderer.setSize( window.innerWidth, window.innerHeight );
//canvas
var canvas = renderer.domElement;
canvas.setAttribute("width",  window.innerWidth);
canvas.setAttribute("height",  window.innerHeight);
document.body.appendChild( canvas );
var perspectiveCamera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight, 1, 200000);
//scene
var rttScene = new Physijs.Scene();

var bounding = new Physijs.SphereMesh(new THREE.SphereGeometry(100, 100, 100),
    Physijs.createMaterial(
        new THREE.MeshBasicMaterial({color: '#ff0000'}),
        1.0, // friction
        0.0 // restitution
        ),50 //mass
    );

bounding.position.set(200,1200,-5000);

loader.load("http://0.0.0.0:8000/Models/Isola/pavimento.js", function( geometry, materials){
    var groundMaterial = Physijs.createMaterial(new THREE.MeshFaceMaterial(materials),
        0.8, // friction
        0.2 // restitution
            );
    floor = new Physijs.ConcaveMesh(geometry,groundMaterial,0);
    floor.name = "pavimento";
    rttScene.add(floor);
    initScene();
    render();
 });

function initScene() {
    rttScene.setGravity(gravityVector);
    rttScene.add(envModel);
    rttScene.add(bounding);
    bounding.setAngularFactor(new THREE.Vector3(0, 0, 0));
    bounding.setCcdMotionThreshold( 0.1 );
    bounding.setCcdSweptSphereRadius( 1 );

    var ambientLight =  new THREE.AmbientLight(0xD9B775 ); 
    rttScene.add(ambientLight);

    var directionalLight = new THREE.DirectionalLight(0xc7af81);
    directionalLight.target.position.copy( rttScene.position );
    directionalLight.position.set(-550,1950,1950).normalize(); 
    directionalLight.intensity = 0.7;
    rttScene.add(directionalLight);

    perspectiveCamera.position.set(200,1200,-3000);
    perspectiveCamera.lookAt(bounding.position);
}

function render() {
    requestAnimationFrame(render);
    renderer.clear();
    rttScene.simulate();

    renderer.render(rttScene, perspectiveCamera);
    }

I also tried this into render() function:

var originPoint = bounding.position.clone();
var ray = new THREE.Raycaster(originPoint, new THREE.Vector3(0, -1, 0));
var collisionResults = ray.intersectObjects(rttScene.children)
if (collisionResults.length > 0) {
    console.log(collisionResults[0].distance);
}

In console i can read the distance between "bounding" and "floor". This should mean that floor exist as a collider but it doesn't stop bounding from falling. Why?


Source: (StackOverflow)

How to get Physijs and Threejs to work together with tQuery

Good evening,

I recently switched from EaselJS to Threejs, it's amazing!

I've tried to include a physic engine called Physijs and use it with tQuery with this tutorial but it's not working.

Head:

<!-- Physics engine -->
<script type="text/javascript" src="lib/tquery-bundle-require.js"></script>
<!-- <script type="text/javascript" src="lib/ammo.js"></script>-->
<script type="text/javascript" src="lib/physi.js"></script>
<script type="text/javascript" src="lib/tquery.physi.js"></script>

<!-- Game and GameCore namespace -->
<script type="text/javascript" src="js/game.js"></script>
<script type="text/javascript" src="js/game.static.js"></script>

Physijs version: latest form GitHub Threejs version 59 (included in tQuery) tquery.physi.js version: unknown, grabbed from the source-code of the tutorial, can't find it anywhere else)

init function called when the page's loading is complete:

var world = tQuery.createWorld().boilerplate({cameraControls: false}).start();
world.tCamera().position.set( 70, 40, 70 );
world.tCamera().lookAt( world.tScene().position );
world.tRenderer().shadowMapEnabled   = true;
world.tRenderer().shadowMapSoft       = true;
world.tRenderer().setClearColorHex( 0xffffff, 1 );
world.enablePhysics();

Error given by FireBug:

TypeError: world.enablePhysics is not a function
world.enablePhysics();

Does anyone know what I can do to fix this problem,? Feel free to talk about alternative too! :)

Thanks!


Source: (StackOverflow)

ThreeJS: PhysiJS on JSON Object

I can't add physics to a loaded JSON model. The model is displaying but I can't add the addEventListener( 'collision', handleCollision ) to it. The console says "undefined" when I add the listener. I tried it with a normal non-loaded Physijs.BoxMesh and it works perfectly. But if i load a json model as a Physijs.BoxMesh it says "undefinded". Can someone help me ? You can see in my code, that I create a non-loaded cube and a loaded json_cube.

cube.addEventListener( 'collision', handleCollision ); -> works.

json_cube.addEventListener( 'collision', handleCollision ); -> do not work.

// cube 
var material = new THREE.MeshBasicMaterial({map: THREE.ImageUtils.loadTexture("Textures/crate.jpg")});
var cube = new Physijs.BoxMesh(new THREE.CubeGeometry(20, 20, 20), material);
cube.position.x = 0;
cube.position.y = 50;
cube.position.z = 0;
scene.add(cube);

//JSON Cube
var loader = new THREE.JSONLoader();
var json_cube = loader.load("uvcube.json", function ( geometry, material ) {
    materials = new THREE.MeshBasicMaterial({
      map: THREE.ImageUtils.loadTexture("Textures/new_layout.png")
    });

    json_cube = new Physijs.BoxMesh( geometry, materials);
    json_cube.scale.set( 10, 10, 10 );

    json_cube.position.x =0;
    json_cube.position.y =50;
    json_cube.position.z =40;
    scene.add(json_cube);
}); 

Source: (StackOverflow)

Using export from clara.io with three.js and physijs

I have a scene I exported from clara.io, and I can import it in a three.js scene. I modified MateiralLoader and ObjectLoader to add textures loading, but I'm facing a problem, cause I'd like to replace the standard meshes by physical meshes. I tried changing THREE.Mesh in ObjectLoader.js by Physijs.BoxMesh (most of the scene consists in cubes).

The meshes actually display correctly, no error in console, but there's no physics attached to it, no collision. I thought maybe because the clara.io export are geometry and not just CubeGeometry, it might be a problem for physijs... I don't know, and I didn't find anything related. Could you maybe just give a direction for me to search? Thanks!

Here are samples of my code:

The script to export from clara.io, given on their website:

var loader = new THREE.ObjectLoader();
loader.load("zebra.json",function ( obj ) {
  scene.add( obj );
});

So I modified ObjectLoader from three.js: at line 287, in the case of loading a Mesh, i tried replacing this:

object = new THREE.Mesh( geometry, material );

By this:

object = new Physijs.BoxMesh( geometry, material );

And I also tried:

object = new Physijs.ConvexMesh( geometry, material );

Or:

object = new Physijs.ConcaveMesh( geometry, material );

I never gets physics (especially collisions) working, although the objects are well displayed in the scene. But collisions work well with for example a cube created directly from the script, using THREE.BoxGeometry, then using it with Physijs.BoxMesh.


Source: (StackOverflow)

Using cannon.js for collision detection in a three.js game

I'm working on something with three.js where i need a way to handle collisions between objects very generally. I was thinking of using cannon.js since it supports the primitives i need but i don't always particularly need/want any of the overhead of the physics (lets say for detecting a bullet hitting a particular enemy), i just mainly want to use it for collision detection in a lot of cases since im not interested in going down the rabbit hole of writing my own general collision detection engine.

Basically what i'm asking is if there's a relatively simple way to use cannon.js, or perhaps some other javascript physics library to test for object/object object/terrain collisions and determine if objects are/aren't colliding. If i could get stuff like penetration depth, the normal of the collision etc. that would be even better.

would i be better off using physijs if i really wanted things to be tightly and effeciently integrated with my three.js code? it seems to also have what i need, but the performance seemed pretty bad from the demos on its main page.

thanks!


Source: (StackOverflow)

Physijs Load model three.js collisions don't work

When I load my model(map) with JSONLoader I have a problem with collisions. If I load with BoxMesh it's work but the geometry collisions is like a cube, and my model is not a cube, the middle of my model is empty. And I put an other object (cube) on the top of my map the object stop on the top of this map not inside.

After search, I have load my model with Convex, and the object ont the top , fall on the plane of my map but I think the size (40) is not load correctly because if I move the object very little he fall in the space.

I load my model like this:

 var loader = new THREE.JSONLoader();
 loader.load( "essai/lobby3.js", function( lobby_geometry, lobby_materials ) {
 console.log(lobby_geometry);
 var ground_material = Physijs.createMaterial(
            new THREE.MeshFaceMaterial(lobby_materials),
            .8, // high friction
            0 // low restitution
        );

    mesh = new Physijs.Mesh ( //I try with BoxMesh / Convex / Concav
                    lobby_geometry,
                    ground_material,
                    0
                );
       mesh.scale.set(40,40,40);
       scene.add(mesh);    
});

I don't know if it's very easy to understand the problem.

BoxMesh: Here the object is stop. sans titre3

Convex: Don't detect collisions sans titre

I upload my tests, I think maybe is better to undestand : http://www.hebergeurfichier.com/download/a97e3ae31c36dfe98525213cde90165f.html

PS: I create my models with blender and export in three.js extension.


Source: (StackOverflow)