Helper object is not updating the target position - javascript

My scene has a cube and a directional light with your Helper.
The cube is placed on X: 300 Y: 100 z: 0 and the light is positioned at X: 300 Y: 600 z: 0.
The Target object of light has the same position of the cube.
But the target of the helper is being drawn at (0, 0, 0).
How do I make drawing Helper point to the target light?
This is my code:
var geometry = new THREE.CubeGeometry(200, 200, 200);
var material = new THREE.MeshPhongMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
cube.position.set(300, 100, 0);
scene.add(cube);
var color = 0xffffff;
var intensity = 1;
var light = new THREE.DirectionalLight( color, intensity );
light.position.set(300, 600, 0);
light.target.position.set(300, 100, 0);
scene.add( light );
var helper = new THREE.DirectionalLightHelper( light, 20 );
scene.add( helper );
helper.update();

Related

Three.js - Align cube to a grid

I am using GridHelper to make a grid and I would like to place a cube directly on top of a grid's tile. Here is my current implementation, which puts a cube on a grid, but it not directly aligned with a tile.
// cubes
cubeGeo = new THREE.BoxGeometry( 50, 50, 50 );
cubeMaterial = new THREE.MeshLambertMaterial( {color: 0xfeb74c } );
var voxel1 = new THREE.Mesh( cubeGeo, cubeMaterial );
scene.add(voxel1);
// grid
var gridHelper = new THREE.GridHelper( 1000, 20 );
console.log(gridHelper);
scene.add( gridHelper );
Grid with Box not align
How would i go about making the box align with the grid ?
You can translate your geometry after it is created, like so:
cubeGeo = new THREE.BoxBufferGeometry( 50, 50, 50 );
cubeGeo.translate( 25, 0, 25 );
If you add additional cubes, you can reuse the same geometry, and set the mesh's position:
voxel.position.set( x, y, z );
three.js r.87

BabylonJS Collision Detection, Overlapping Meshes

In the following example: http://www.babylonjs-playground.com/#1NASOD#13
Why does the sphere mesh overlap (or fall slightly into) the box mesh as the box moves upwards? Is there a way to make the sphere not overlap the box as the box moves the sphere upwards?
For reference, here is the relevant code from the example:
var createScene = function () {
// This creates a basic Babylon Scene object (non-mesh)
var scene = new BABYLON.Scene(engine);
// This creates and positions a free camera (non-mesh)
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 10, -20), scene);
// This targets the camera to scene origin
camera.setTarget(BABYLON.Vector3.Zero());
// This attaches the camera to the canvas
camera.attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
var sphere = BABYLON.Mesh.CreateSphere("sphere1", 8, 2, scene);
// Move the sphere upward 1/2 its height
sphere.position.y = 2;
var ground = BABYLON.Mesh.CreateBox("box1",2.0, scene);
ground.position.y = -1;
sphere.material = new BABYLON.StandardMaterial("s-mat", scene);
scene.enablePhysics(new BABYLON.Vector3(0, 0, 0));
sphere.physicsImpostor = new BABYLON.PhysicsImpostor(sphere, BABYLON.PhysicsImpostor.SphereImpostor, { mass: 1, restitution: 0 }, scene);
ground.physicsImpostor = new BABYLON.PhysicsImpostor(ground, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 0, restitution: 0 }, scene);
scene.registerBeforeRender(function () {
if(ground.position.y <= 2.5){
ground.position.y += .05;
}
sphere.physicsImpostor.setLinearVelocity(new BABYLON.Vector3(0,0,0));
sphere.physicsImpostor.setAngularVelocity(new BABYLON.Quaternion(0,0,0,0));
});
return scene;
};

Avoid overlapping of planegeometry in Threejs

I have added sphere and planegeometry to the scene, I have used X and Y values to place the planegeometry in
the scene, some planegeometry are overlapping with eachother I need to detect the overlapped planegeometry
and place it to a new position in order to avoid the overlapping of those planegeometry without changing the
X and Y values. can someone please help me how to solve this problem. I have just added this code in jsfiddle
I don't know exactly how to display result in jsfiddle. I have added the image of the result which might give
an idea what the problem is. https://jsfiddle.net/lakers1234/ek7fcx9L/
window.onload = createsphere();
function createsphere()
{
var controls,scene,camera,renderer;
function init()
{
var spriteResponse = [];
spriteResponse[0] = {ID:1, x: 0, y: 0, name:'Hello'};
spriteResponse[1] = {ID:2, x: 0, y: 0.01, name:'Hello world'};
spriteResponse[2] = {ID:3, x: 0, y: 0.5, name:'los Angles united states of america'};
spriteResponse[3] = {ID:4, x: 0.5, y: 0, name:'Canada'};
spriteResponse[4] = {ID:5, x: 0.25, y: 0.5, name:'London united kingdom' };
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
//camera.position.y = 1;
camera.position.z = 1 ;
var width = window.innerWidth;
var height = window.innerHeight;
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
/* ------------------------ creating the geometry of sphere------------------------------*/
var radius = 2.5;
var spheregeometry = new THREE.SphereGeometry(radius, 20, 20, 0, -6.283, 1, 1);
var texture = THREE.ImageUtils.loadTexture ('rbi00000083.jpg');
texture.minFilter = THREE.NearestFilter;
//var spherematerial = new THREE.MeshBasicMaterial({map: texture});
var spherematerial = new THREE.MeshBasicMaterial({color: '#A9A9A9'});
var sphere = new THREE.Mesh(spheregeometry, spherematerial);
scene.add(sphere);
scene.add(camera);
scene.autoUpdate = true;
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.minPolarAngle = Math.PI/4;
controls.maxPolarAngle = 3*Math.PI/4;
}
Based on this SO answer.
When you know quaternion of your camera, you can apply it to your planes.
Put your planes in an array:
var planes = [];
and then in the animation loop we'll do this:
planes.forEach(function(p){
p.quaternion.copy(camera.quaternion);
})
jsfiddle example.

Rotating a 3d vector in THREE.js on two axes

Sorry for posting possible duplicate.
I have two 3d vectors:
center ( 0, 0, 0 )
orb ( 0, 0, 100 )
I want to rotate the orb-vector around the center-vector on both X and the Y axes.
What I'm trying to achieve is the make and object always be in view of the camera in the direction it's facing.
I've tried this but with no luck.
var vector = new THREE.Vector3( 0, 0, 100 );
vector.applyAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI * 0.5 );
vector.applyAxisAngle( new THREE.Vector3( 1, 0, 0 ), Math.PI * 0.5 );
orbBall.position.copy(vector);
"What I'm trying to achieve is the make and object always be in view of the camera in the direction it's facing."
If you are simply trying to ensure that orbBall always faces the camera, and both orbBall and the camera are part of the THREE scene then you can just use lookAt like so:
orbBall.lookAt(camera.position);
if you need to align a particular side of orbBall you can use a null dummy Object3D to do it, by adding the dummy node to the scene and orbBall to the dummy, in something like this:
dummy = new THREE.Object3D();
scene.add(camera); // "camera" is defined however
scene.add(dummy);
dummy.add(orbBall); // "orbBall" is created as usual
// ... not to align dummy+orbBall
dummy.lookAt(camera.position);
// ...and you can just rotate orbBall around "inside" dummy, just once,
/// to face however you like
After digging around this issue I realise that it's quite advanced mathematics.
Check out this lecture about quaternions if you're interested:
https://www.youtube.com/watch?v=mHVwd8gYLnI
So I used #bjorke suggestins and used a dummy object, and it works well.
var container, scene, camera, renderer, controls, stats;
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(100, 100, 400);
camera.lookAt(scene.position);
scene.add(camera);
renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
var light = new THREE.DirectionalLight(0xffffff); //new THREE.PointLight(0xffffff);
light.position.set( 30, 80, -15 );
scene.add(light);
var boxGeo = new THREE.BoxGeometry( 10, 10, 10);
var axes = new THREE.AxisHelper(1000);
scene.add( axes );
var cameraObj = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x888800}));
scene.add(cameraObj);
var orbSpace = new THREE.Object3D();
scene.add(orbSpace);
var orbBall = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x880088}));
orbBall.position.set(0, 0, cameraObj.position.z + 100);
orbSpace.add(orbBall);
animate();
var camX = 0.3;
var camY = 0;
function animate() {
requestAnimationFrame( animate );
camY += 0.02;
if (camY >= 2) camY = 0;
cameraObj.rotation.x = Math.PI * document.querySelector('#volume').value;
cameraObj.rotation.y = Math.PI * camY;
orbSpace.position.copy(cameraObj.position);
orbSpace.rotation.copy(cameraObj.rotation)
renderer.render( scene, camera );
}
Here's a codepen about how it works:
http://codepen.io/arpo/pen/RrpMJJ
You can update the X angle in the uper right corner

Three.js Object3d cylinder rotation to align to a vector

I have searched far and wide, but can't seem to figure this pretty basic thing out. I have seen other examples on stackoverflow and elsewhere from a year or two ago, but they fail to work with the latest version of Three.js.
Here is a version of what i'm working on: http://medschoolgunners.com/sandbox/3d/.
I'm trying to get the grey cone to exactly align with the unlabeled red vector. Ie. I want the tip of the cone to be exactly aligned with the vector and point out from the origin in that direction.
Here is the code I have right now:
//FUNCTION TO CREATE A CYLINDER
function create_cylinder(radiusTop,radiusBottom, height, segmentsRadius, segmentsHeight, openEnded, color)
{
var material = new THREE.MeshLambertMaterial({
color: color, //0x0000ff
opacity: 0.2
});
var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(radiusTop,radiusBottom, height, segmentsRadius, segmentsHeight, openEnded), material);
cylinder.overdraw = true;
return cylinder;
}
//ALIGN THE CYLINDER TO A GIVEN VECTOR
var alignVector=new THREE.Vector3(-50,50,50); //the vector to be aligned with
var newcylinder = create_cylinder(0.1, 10, 40, 50, 50, false, "0x0ff0f0"); // the object to be aligned with the vector above
var cylinderQuaternion = new THREE.Quaternion();
cylinderQuaternion.setFromEuler(alignVector);
newcylinder.useQuaternion = true;
newcylinder.quaternion=cylinderQuaternion;
scatterPlot.add(newcylinder);
If you have an arbitrary vector:
var vector = new THREE.Vector3(100, 60, 20);
You can align an object, such as a cylinder, to the vector like this:
var geometry = new THREE.CylinderGeometry(2, 2, vector.length(), 4, 4);
var mesh = new THREE.Mesh(geometry, someMaterial);
var axis = new THREE.Vector3(0, 1, 0);
mesh.quaternion.setFromUnitVectors(axis, vector.clone().normalize());
Where axis is the original direction of the cylinder (pointing up).
You can also move the cylinder to match the position of the vector like this:
mesh.position.copy(vector.clone().multiplyScalar(0.5));
This puts one end of the cylinder at the 0, 0, 0 and the other at 100, 60, 20, and works because I set the cylinder length to vector.length().
i know this is an old question, but in case anyone is still wondering, what worked for me was adding the vector to the mesh position and use lookAt to align it to the vector:
//Mesh to align
var material = new THREE.MeshLambertMaterial({color: 0x0000ff});
var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(10, 10, 15), material);
//vector to align to
var vector = new THREE.Vector3(
5,//x
10,//y
15 //z
);
//create a point to lookAt
var focalPoint = new THREE.Vector3(
cylinder.position.x + vector.x,
cylinder.position.y + vector.y,
cylinder.position.z + vector.z
);
//all that remains is setting the up vector (if needed) and use lookAt
cylinder.up = new THREE.Vector3(0,0,1);//Z axis up
cylinder.lookAt(focalPoint);
Unfortunately I haven't worked with Quaternions, so can't help much. It seems to my that some offsetting is needed, since the cylinder's pivot is at the centre of the mesh, not at one end.
If played with matrices a bit, and I've got decent results.
Here's one way to this, using Mesh's lookAt() method:
var HALF_PI = -Math.PI * .5;
var p1 = new THREE.Vector3(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(30);
var p2 = new THREE.Vector3(Math.random(),Math.random(),Math.random()).multiplyScalar(300);
var halfLength = diff.length() * .5;
var c = new THREE.CylinderGeometry(10, 10, halfLength * 2, 12, 1, false );
var orientation = new THREE.Matrix4();
orientation.setRotationFromEuler(new THREE.Vector3(HALF_PI,0,0));//rotate on X 90 degrees
orientation.setPosition(new THREE.Vector3(0,0,halfLength));//move half way on Z, since default pivot is at centre
c.applyMatrix(orientation);//apply transformation for geometry
var m = new THREE.Mesh( c, new THREE.MeshLambertMaterial( { color: 0x009900, wireframe: true, shading: THREE.FlatShading } ) );
scene.add(m);
m.lookAt(p2);//tell mesh to orient itself towards p2
//just for debugging - to illustrate orientation
m.add(new THREE.Axes());
//visualize p1,p2 vectors
var PI2 = Math.PI * 2;
var program = function ( context ) {
context.beginPath();
context.arc( 0, 0, 1, 0, PI2, true );
context.closePath();
context.fill();
}
particleMaterial = new THREE.ParticleCanvasMaterial( { color: 0x990000, program: program } );
var pp1 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x990000, program: program } ) );
pp1.scale.multiplyScalar(10);
pp1.position.copy(p1);
scene.add( pp1 );
var pp2 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x009900, program: program } ) );
pp2.scale.multiplyScalar(10);
pp2.position.copy(p2);
scene.add( pp2 );
This should draw a cylinder that starts at p1, ends at p2 and is oriented towards it.
Offsetting might need some tweaking, but the geometry follows the vector direction pretty close.
There's also the longer version of manually computing the matrices, as opposed to relying on the lookAt() functionality:
plane.add(getCylinderBetweenPoints(p1,p2,new THREE.MeshLambertMaterial( { color: 0x009900, wireframe: true, shading: THREE.FlatShading } )));
function getCylinderBetweenPoints(point1,point2,material){
var HALF_PI = -Math.PI * .5;
var diff = new THREE.Vector3().sub(point1,point2);//delta vector
var halfLength = diff.length() * .5;
var c = new THREE.CylinderGeometry(10, 10, halfLength * 2, 12, 1, false );
var orientation = new THREE.Matrix4();//a new orientation matrix to offset pivot
var offsetRotation = new THREE.Matrix4();//a matrix to fix pivot rotation
var offsetPosition = new THREE.Matrix4();//a matrix to fix pivot position
orientation.lookAt(point1,point2,new THREE.Vector3(0,1,0));//look at destination
offsetRotation.setRotationX(HALF_PI);//rotate 90 degs on X
offsetPosition.setPosition(new THREE.Vector3(-point1.x,diff.length()*.5+point1.z,point1.y*.5));//move by pivot offset on Y
orientation.multiplySelf(offsetRotation);//combine orientation with rotation transformations
orientation.multiplySelf(offsetPosition);//combine orientation with position transformations
c.applyMatrix(orientation);//apply the final matrix
var m = new THREE.Mesh( c, material );
m.add(new THREE.Axes());
return m;
}
var PI2 = Math.PI * 2;
var program = function ( context ) {
context.beginPath();
context.arc( 0, 0, 1, 0, PI2, true );
context.closePath();
context.fill();
}
//visualize p1,p2 vectors
particleMaterial = new THREE.ParticleCanvasMaterial( { color: 0x990000, program: program } );
var pp1 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x990000, program: program } ) );
pp1.scale.multiplyScalar(10);
pp1.position.copy(p1);
plane.add( pp1 );
var pp2 = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x009900, program: program } ) );
pp2.scale.multiplyScalar(10);
pp2.position.copy(p2);
plane.add( pp2 );
This looks like me more work than using quaternion, from what I see in you're code. If the setFromEuler does the magic for orientation, the mesh's geometry still might need to move (pivot from one end rather than centre)
HTH

Categories