I have an issue while using PhysiJS and Three JS, I can't handle collision event.
Repository on Github : https://github.com/kevrmnd/soccer-physics (in script.js file)
I have a ground and a ball, I put an eventlistener on the ball which should alert or log something when it falls on the ground but there is no output.
Here is how I set scene and gravity :
scene = new Physijs.Scene({ fixedTimeStep: 1 / 120 });
scene.setGravity( new THREE.Vector3( 0, -30, 0 ) );
Here is my ground :
loader = new THREE.TextureLoader();
// Materials
ground_material = Physijs.createMaterial(
new THREE.MeshStandardMaterial({ map: loader.load( 'img/grass.png' ) }),
1,
0.6
);
ground_material.map.wrapS = ground_material.map.wrapT = THREE.RepeatWrapping;
ground_material.map.repeat.set( 4, 4 );
// Ground
ground = new Physijs.BoxMesh(
new THREE.BoxGeometry( 30 , 1, 60 ),
ground_material,
0
);
ground.receiveShadow = true;
scene.add( ground );
And finally my ball :
shape_material = Physijs.createMaterial(
new THREE.MeshNormalMaterial(),
0.5, // low friction
0.8 // high restitution
);
shape = new Physijs.SphereMesh(
new THREE.SphereGeometry( 0.5, 25, 25 ),
shape_material,
0.75
);
shape.addEventListener( 'collision', function(){
alert( 'hey' );
} );
shape.position.z = 20;
scene.add( shape );
I really don't understand why this doesn't trigger an event. I need your help :-)
Ok I found the solution here : https://github.com/chandlerprall/Physijs/issues/248
Just had to modify two lines in physijs_worker.js file !
Related
I'm attempting to create a sphere in three.js with a base material and a transparent png material over the top. I found this answer helpful in understanding how to load multiple materials. However when I try to apply this to SphereGeometry rather than BoxGeometry as in the example, only the second material is visible, with no transparency.
http://jsfiddle.net/oyamg8n3/1/
// geometry
var geometry = new THREE.BoxBufferGeometry( 10, 10, 10 );
geometry.clearGroups();
geometry.addGroup( 0, Infinity, 0 );
geometry.addGroup( 0, Infinity, 1 );
geometry.addGroup( 0, Infinity, 2 );
geometry.addGroup( 0, Infinity, 3 );
// textures
var loader = new THREE.TextureLoader();
var splodge = loader.load( 'https://threejs.org/examples/textures/decal/decal-diffuse.png', render );
var cat = loader.load('https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80.jpeg', render)
// materials
var catMat = new THREE.MeshPhongMaterial( {
map: cat,
} );
var splodgeMat = new THREE.MeshPhongMaterial( {
map: splodge,
alphaTest: 0.5,
} );
var materials = [ catMat, splodgeMat ];
// mesh
mesh = new THREE.Mesh( geometry, materials );
scene.add( mesh );
Can I use these same principles for
var geometry = new THREE.SphereGeometry( 5, 20, 20 );
It does work if you use SphereBufferGeometry and not SphereGeometry. Notice that both classes have a different super class. You want to work with the BufferGeometry version.
Demo: http://jsfiddle.net/r6j8otz9/
three R105
I have been trying to create in three.js a rope hanging from a point using any of the 3D physics libraries (ammo.js, cannon.js), but the only one I have successfully done is with (2D)verlet.js.
I really need and want to create it in 3D because I need two ropes attached to a midpoint so that I can show the instability of the midpoint as a load is applied. Something similar as the attached image.
enter image description here
To be honest, I have not idea how to start, I have some experience with Three.js, but non with ammo.js or cannon.js. So far I have been trying to understand the codes for the examples in these links with not success.
http://schteppe.github.io/cannon.js/demos/constraints.html
https://threejs.org/examples/#webgl_physics_rope
I even tried to make a rope using spring function from cannon.js, but you can see that my example is not success.
Can somebody please help me or guide me into the correct way to begin my task?
This is the Code I began to write using Cannon.js:
function initCannon()
{
world = new CANNON.World();
world.gravity.set(.2,-10,.2);
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 10;
var mass = 1;
var damping = 1;
// STATIC SPHERE
var sphereShape = new CANNON.Sphere(new CANNON.Vec3(1,1,1));
mass = 0;
sphereBody = new CANNON.Body({ mass: 0 });
sphereBody.addShape(sphereShape);
sphereBody.position.set(.5,8,.5);
world.addBody(sphereBody);
// DINAMIC SPHERE 1
var shape = new CANNON.Sphere(new CANNON.Vec3(1,1,1));
body = new CANNON.Body({ mass: 1 });
body.addShape(shape);
body.angularDamping = damping;
body.position.set(0,8,0);
world.addBody(body);
// DINAMIC SPHERE 2
var shape2 = new CANNON.Sphere(new CANNON.Vec3(1,1,1));
body2 = new CANNON.Body({ mass: 1 });
body2.addShape(shape2);
body2.angularDamping = damping;
body2.position.set(0,8,0);
world.addBody(body2);
// DINAMIC SPHERE 3
var shape3 = new CANNON.Sphere(new CANNON.Vec3(1,1,1));
body3 = new CANNON.Body({ mass: 1 });
body3.addShape(shape3);
body3.angularDamping = damping;
body3.position.set(0,8,0);
world.addBody(body3);
var size = 1;
var rebote = 1;
var spring = new CANNON.Spring(body,sphereBody,{
localAnchorA: new CANNON.Vec3(0,size,0),localAnchorB: new CANNON.Vec3(0,0,0),
restLength : 0, stiffness : 50, damping : rebote, });
var spring2 = new CANNON.Spring(body2, body,{
localAnchorA: new CANNON.Vec3(0,size,0),localAnchorB: new CANNON.Vec3(0,0,0),
restLength : 0, stiffness : 50, damping : rebote, });
var spring3 = new CANNON.Spring(body3, body2,{
localAnchorA: new CANNON.Vec3(0,size,0),localAnchorB: new CANNON.Vec3(0,0,0),
restLength : 0, stiffness : 50, damping : rebote, });
world.addEventListener("postStep",function(event){ spring.applyForce(); });
world.addEventListener("postStep",function(event){ spring2.applyForce(); });
world.addEventListener("postStep",function(event){ spring3.applyForce(); });
}
function initThree()
{
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 100 );
camera.position.y = 3;camera.position.z = 15;
scene.add( camera );
controls = new THREE.TrackballControls( camera );
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.keys = [ 65, 83, 68 ];
var material_wire = new THREE.MeshBasicMaterial( { color: 0xFFFFFF, wireframe: true } );
var sphere_size = .8;
var segmentos = 5;
geometry_sphere = new THREE.SphereGeometry( sphere_size, segmentos, segmentos );
sphere = new THREE.Mesh( geometry_sphere, material_wire );
scene.add( sphere );
geometry = new THREE.SphereGeometry( sphere_size, segmentos,segmentos ); // RRT DEFINE TAMANO DE CUBE
mesh = new THREE.Mesh( geometry, material_wire );
scene.add( mesh );
mesh2 = new THREE.Mesh( geometry, material_wire );
scene.add( mesh2 );
mesh3 = new THREE.Mesh( geometry, material_wire );
scene.add( mesh3 );
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
controls.update();
updatePhysics();
render();
}
function updatePhysics() {
// Step the physics world
world.step(timeStep);
sphere.position.copy(sphereBody.position);
mesh.position.copy(body.position); // HACE QUE SE VEA
mesh2.position.copy(body2.position);
mesh3.position.copy(body3.position);
}
function render() {
renderer.render( scene, camera );
}
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?
I'm would like to create multiple cubes, add a click-event on each one of them and combine them in a "parent" object with GeometryUtils.merge.
var cubes=[];
var mainGeom = new THREE.Geometry();
var cubegeometry = new THREE.CubeGeometry(50, 50, 50, 1, 1, 1 );
cubes[1] = new THREE.Mesh( cubegeometry );
cubes[1].position.y = -50;
THREE.GeometryUtils.merge( mainGeom, cubes[1] );
cubes[2] = new THREE.Mesh( cubegeometry );
cubes[2].position.y = 50;
THREE.GeometryUtils.merge( mainGeom, cubes[2] );
cubes[3] = new THREE.Mesh( cubegeometry );
cubes[3].position.z = -50;
THREE.GeometryUtils.merge( mainGeom, cubes[3] );
cube = new THREE.Mesh( mainGeom,new THREE.MeshBasicMaterial( { color: 0xff0000 } ));
Combining is working fine.
But how can i add a click event on each one of them? I am using this:
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse = {x : ( event.clientX / window.innerWidth ) * 2 - 1, y :- ( event.clientY / window.innerHeight ) * 2 + 1 };
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
projector.unprojectVector( vector, camera );
var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = raycaster.intersectObjects( cube );
if ( intersects.length > 0 ) {
console.log(intersects);
}
}
But the intersects.length is always 0!
What am I doing wrong?
Thanks a lot!
Regards - Kosha
GeorgeProfenza has given me a good hint. The solution was to add these Subobject to a parent object, then - this was the solution! Thanks
I've recently converted my scene to using a WebGLDeferredRenderer as it's easier for me to implement SSAO. However, since converting to the deferred renderer I'm unable to render THREE.Line objects. Instead, I get the following error:
THREE.Material: 'shading' parameter is undefined.
This is the code for the lines (a grid) that works fine when I'm not using a deferred renderer:
var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3( -2500, 0, 0 ) );
geometry.vertices.push( new THREE.Vector3( 2500, 0, 0 ) );
linesMaterial = new THREE.LineBasicMaterial( {color: 0xb9b9b9, linewidth: 0.1} );
for ( var i = 0; i <= 50; i ++ ) {
var line = new THREE.Line( geometry, linesMaterial );
line.position.z = ( i * 100 ) - 2500;
scene.add( line );
var line = new THREE.Line( geometry, linesMaterial );
line.position.x = ( i * 100 ) - 2500;
line.rotation.y = 90 * Math.PI / 180;
scene.add( line );
}
I've tried adding a shading property to the THREE.LineBasicMaterial with a value such as THREE.FlatShading but I still get the same error.
The error is being reported from the THREE.Material section of the main three.js script. If it helps, I'm using a slightly customised version of three.js – http://alteredqualia.com/three/examples/js/three.max.deferredday.js
Any and all help is appreciated!
Update
Here is a quick hack with the public version of Three.js exhibiting this problem.
That is because lines and LineBasicMaterial are not supported (yet) with WebGLDeferredRenderer.
As a work-around, you can do this:
var geometry = new THREE.PlaneGeometry( 5000, 5000, 50, 50 );
var material = new THREE.MeshBasicMaterial( { color: 0xb9b9b9, wireframe: true } );
scene.add( new THREE.Mesh( geometry, material ) );
Unfortunately material.wireframeLinewidth is not supported either.
three.js r.55