Three.js - Rotate object along (0,0,0) on mouse move - javascript

I have this object here in Three.js. The object has been implemented on blender and i have imported it in three.js format. What i want is to rotate the object with my mouse. If someone could help i would really appreciate it! Thanks
function init(x, y, z, base, small, big, corners) {
scene = new THREE.Scene();
initMesh(x, y, z, base, small, big, corners);
initCamera();
initLights();
initRenderer();
var e = document.body.appendChild(renderer.domElement);
e.style.marginLeft="300px";
e.style.position="absolute";
render();
}
function initCamera() {
camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
camera.position.set(0, 3.5, 3);
camera.lookAt(scene.position);
}
function initRenderer() {
renderer = new THREE.WebGLRenderer({ antialias: true});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor("white");
}
var mesh = null;
var mesh1 = null;
var mesh2 = null;
var mesh3 = null;
var group;
function initMesh(x, y, z, base, small, big, corners) {
group = new THREE.Object3D();
var loader = new THREE.JSONLoader();
loader.load(base, function(geometry, materials) {
mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh.scale.x = x;
mesh.scale.y = y;
mesh.scale.z = z;
mesh.opacity=1;
mesh.castShadow = false;
var model = new THREE.Object3D();
model.add(mesh);
model.position.set(0,0,0);
//mesh.translation = THREE.GeometryUtils.center(geometry);
group.add(model);
});
loader.load(small, function(geometry, materials) {
mesh1 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh1.scale.x = x;
mesh1.scale.y = y;
mesh1.scale.z = z;
mesh1.opacity=1;
mesh1.castShadow = false;
var model1 = new THREE.Object3D();
model1.add(mesh1);
model1.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model1);
});
loader.load(big, function(geometry, materials) {
mesh2 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh2.scale.x = x;
mesh2.scale.y = y;
mesh2.scale.z = z;
mesh2.opacity=1;
mesh2.castShadow = false;
var model2 = new THREE.Object3D();
model2.add(mesh2);
model2.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model2);
});
loader.load(corners, function(geometry, materials) {
mesh3 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh3.scale.x = x;
mesh3.scale.y = y;
mesh3.scale.z = z;
mesh3.opacity=1;
mesh3.castShadow = false;
var model3 = new THREE.Object3D();
model3.add(mesh3);
model3.position.set(0,0,0);
//mesh1.translation = THREE.GeometryUtils.center(geometry);
group.add(model3);
});
scene.add(group);
}
function initLights() {
var light; // A light shining from the direction of the camera.
light = new THREE.DirectionalLight();
light.position.set(0,100,10);
group.castShadow = false;
group.receiveShadow = false;
scene.add(light);
}
function rotateMesh() {
if (!mesh) {
return;
}
//group.rotation.y -= 0.4* ( Math.PI / 180 );
}
function render() {
requestAnimationFrame(render);
rotateMesh();
renderer.render(scene, camera);
}
init(0.5, 0.5, 0.5, "base.js", "small.js", "big.js", "corners.js");

To whom it may concern i found the answer here. In my case root must become group
var mouseDown = false,
mouseX = 0,
mouseY = 0;
function onMouseMove(evt) {
if (!mouseDown) {
return;
}
evt.preventDefault();
var deltaX = evt.clientX - mouseX,
deltaY = evt.clientY - mouseY;
mouseX = evt.clientX;
mouseY = evt.clientY;
rotateScene(deltaX, deltaY);
}
function onMouseDown(evt) {
evt.preventDefault();
mouseDown = true;
mouseX = evt.clientX;
mouseY = evt.clientY;
}
function onMouseUp(evt) {
evt.preventDefault();
mouseDown = false;
}
var ee = document.body.appendChild(renderer.domElement);
ee.addEventListener('mousemove', function (e) {
onMouseMove(e);
}, false);
ee.addEventListener('mousedown', function (e) {
onMouseDown(e);
}, false);
ee.addEventListener('mouseup', function (e) {
onMouseUp(e);
}, false);
var c=1;
var cc=3;
var ccc=3;
ee.addEventListener('wheel', function (e) {
console.log(e.deltaY);
if(e.deltaY>0){
c=c*0.95
cc=cc*0.95;
ccc=ccc*0.95
camera.position.set(c, cc, ccc);
}else{
c=c*1.05
cc=cc*1.05;
ccc=ccc*1.05
camera.position.set(c, cc, ccc);}
});
function rotateScene(deltaX, deltaY) {
group.rotation.y += deltaX / 100;
group.rotation.x += deltaY / 100;
}
I added a zoom function too, it needs this lib here

Related

How to remove transparency here

How to i remove the clipped objects that have become transparent or prevent the object below it from being shown.
It would be better if it looks like a real world solid cubes.
This is written in javascript with three.js. HTML and CSS have no faults. Only the rendering shows issue here.
var scene, camera, renderer, cube;
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var SPEED = 0.001;
function init() {
scene = new THREE.Scene();
initLight();
drawScene();
initCamera();
initRenderer();
document.body.appendChild(renderer.domElement);
}
function initLight() {
const light = new THREE.PointLight(0xFFFFFF);
light.position.x = 50;
light.position.y = 50;
light.position.z = 130;
scene.add(light);
}
function initCamera() {
camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
camera.position.set(1, 3, 5);
camera.lookAt(scene.position);
}
function initRenderer() {
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(WIDTH, HEIGHT);
renderer.sortObjects = false;
}
function drawScene() {
var material = new THREE.MeshLambertMaterial({ color: 0xFF6600 });
var shape = new THREE.CubeGeometry(1, 1, 1);
cube = new THREE.Group();
for (var a = -10; a <= 10; a = a + 2) {
for (var b = -10; b <= 10; b = b + 2) {
for (var c = -10; c <= 10; c = c + 2) {
var part = new THREE.Mesh(shape, material);
part.position.set(a, b, c);
cube.add(part);
}
}
}
scene.add(cube);
}
function rotateCube() {
cube.rotation.x -= SPEED;
cube.rotation.y -= SPEED;
cube.rotation.z -= SPEED;
}
function render() {
requestAnimationFrame(render);
rotateCube();
renderer.render(scene, camera);
}
init();
render();
<script src="https://threejs.org/build/three.js"></script>
I changed the PerspectiveCamera near plane closer, to 0.01 instead of 1, and added the includes to make your snippet run.
The "transparency" you're seeing are the cubes clipping against the camera near plane. By pulling the plane closer to the camera, you're making the viewport smaller in the world, so it more easily fits in between the cubes.
Another thing is backface culling.. that makes cubes invisible if they are viewed from inside. You can disable backface culling via material.side = THREE.DoubleSide, at the cost of potentially rendering twice as much geometry.
var scene, camera, renderer, cube;
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var SPEED = 0.001;
function init() {
scene = new THREE.Scene();
initLight();
drawScene();
initCamera();
initRenderer();
document.body.appendChild(renderer.domElement);
}
function initLight() {
const light = new THREE.PointLight(0xFFFFFF);
light.position.x = 50;
light.position.y = 50;
light.position.z = 130;
scene.add(light);
}
function initCamera() {
camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 0.01, 10);
camera.position.set(1, 3, 5);
camera.lookAt(scene.position);
}
function initRenderer() {
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(WIDTH, HEIGHT);
renderer.sortObjects = false;
}
function drawScene() {
var material = new THREE.MeshLambertMaterial({ color: 0xFF6600, side: THREE.DoubleSide});
var shape = new THREE.CubeGeometry(1, 1, 1);
cube = new THREE.Group();
for (var a = -10; a <= 10; a = a + 2) {
for (var b = -10; b <= 10; b = b + 2) {
for (var c = -10; c <= 10; c = c + 2) {
var part = new THREE.Mesh(shape, material);
part.position.set(a, b, c);
cube.add(part);
}
}
}
scene.add(cube);
}
function rotateCube() {
cube.rotation.x -= SPEED;
cube.rotation.y -= SPEED;
cube.rotation.z -= SPEED;
}
function render() {
requestAnimationFrame(render);
rotateCube();
renderer.render(scene, camera);
}
init();
render();
<script src="https://threejs.org/build/three.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>

Why is this threejs sphere not working on mobile?

I have this 3d sphere like halfway done. Its just working pretty slow on desktop, and doesnt even run on mobile. Could one of you guys take a look, and let me know what im doing wrong.
heres the threejs code
window.log = function()
{
if (this.console)
{
console.log(Array.prototype.slice.call(arguments));
}
};
// Namespace
var Defmech = Defmech ||
{};
Defmech.RotationWithQuaternion = (function()
{
'use_strict';
var container;
var camera, scene, renderer;
var sphere;
var mouseDown = false;
var rotateStartPoint = new THREE.Vector3(0, 0, 1);
var rotateEndPoint = new THREE.Vector3(0, 0, 1);
var curQuaternion;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var rotationSpeed = 2;
var lastMoveTimestamp,
moveReleaseTimeDelta = 50;
var startPoint = {
x: 0,
y: 0
};
var deltaX = 0,
deltaY = 0;
var setup = function()
{
container = document.createElement('div');
document.body.appendChild(container);
var info = document.createElement('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Pick you favorite color';
container.appendChild(info);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
// Cube
var sphereGeometry = new THREE.SphereGeometry(200, 200, 200);
var material = new THREE.MeshPhongMaterial();
material.map = THREE.ImageUtils.loadTexture('/color.jpg');
sphere = new THREE.Mesh(sphereGeometry, material);
sphere.position.y = 100;
scene.add(sphere);
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
window.addEventListener('resize', onWindowResize, false);
animate();
};
function onWindowResize()
{
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseDown(event)
{
event.preventDefault();
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
mouseDown = true;
startPoint = {
x: event.clientX,
y: event.clientY
};
rotateStartPoint = rotateEndPoint = projectOnTrackball(0, 0);
}
function onDocumentMouseMove(event)
{
deltaX = event.x - startPoint.x;
deltaY = event.y - startPoint.y;
handleRotation();
startPoint.x = event.x;
startPoint.y = event.y;
lastMoveTimestamp = new Date();
}
function onDocumentMouseUp(event)
{
if (new Date().getTime() - lastMoveTimestamp.getTime() > moveReleaseTimeDelta)
{
deltaX = event.x - startPoint.x;
deltaY = event.y - startPoint.y;
}
mouseDown = false;
document.removeEventListener('mousemove', onDocumentMouseMove, false);
document.removeEventListener('mouseup', onDocumentMouseUp, false);
}
function projectOnTrackball(touchX, touchY)
{
var mouseOnBall = new THREE.Vector3();
mouseOnBall.set(
clamp(touchX / windowHalfX, -1, 1), clamp(-touchY / windowHalfY, -1, 1),
0.0
);
var length = mouseOnBall.length();
if (length > 1.0)
{
mouseOnBall.normalize();
}
else
{
mouseOnBall.z = Math.sqrt(1.0 - length * length);
}
return mouseOnBall;
}
function rotateMatrix(rotateStart, rotateEnd)
{
var axis = new THREE.Vector3(),
quaternion = new THREE.Quaternion();
var angle = Math.acos(rotateStart.dot(rotateEnd) / rotateStart.length() / rotateEnd.length());
if (angle)
{
axis.crossVectors(rotateStart, rotateEnd).normalize();
angle *= rotationSpeed;
quaternion.setFromAxisAngle(axis, angle);
}
return quaternion;
}
function clamp(value, min, max)
{
return Math.min(Math.max(value, min), max);
}
function animate()
{
requestAnimationFrame(animate);
render();
}
function render()
{
if (!mouseDown)
{
var drag = 0.95;
var minDelta = 0.05;
if (deltaX < -minDelta || deltaX > minDelta)
{
deltaX *= drag;
}
else
{
deltaX = 0;
}
if (deltaY < -minDelta || deltaY > minDelta)
{
deltaY *= drag;
}
else
{
deltaY = 0;
}
handleRotation();
}
renderer.render(scene, camera);
}
var handleRotation = function()
{
rotateEndPoint = projectOnTrackball(deltaX, deltaY);
var rotateQuaternion = rotateMatrix(rotateStartPoint, rotateEndPoint);
curQuaternion = sphere.quaternion;
curQuaternion.multiplyQuaternions(rotateQuaternion, curQuaternion);
curQuaternion.normalize();
sphere.setRotationFromQuaternion(curQuaternion);
rotateEndPoint = rotateStartPoint;
};
// PUBLIC INTERFACE
return {
init: function()
{
setup();
}
};
})();
document.onreadystatechange = function()
{
if (document.readyState === 'complete')
{
Defmech.RotationWithQuaternion.init();
}
};
heres a running demo (only works on desktop)
http://wander.ventures/sphere.html
everything works as it should on desktop, although its a bit slow, but on mobile safari, i wasnt even able to move the sphere.

three.js[83] points vertices update not work [duplicate]

I am using Three.js r83.
I am trying to dynamically add points to a geometry, but the scene never gets updated.
This works :
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.computeVertexNormals();
scene.add(pointCloud);
This doesn't work:
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
scene.add(pointCloud);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.elementsNeedUpdate = true;
tgeometry.computeVertexNormals();
renderer.render(scene, camera);
As you can see, the only difference is the fact that I add scene.add(pointCloud); before adding vertexes.
What do I miss?
You can find a fiddle Thanks to #hectate
To see what I means, just replace
init();
setPoints();
animate();
by
init();
animate();
setPoints();
I am not sure why the THREE.Geometry object doesn't update Points after initial rendering, but I got it working with a THREE.BufferGeometry instead.
Thanks to #Hectate who got a working fiddle for me and #WestLangley who directed me to the hints, here is the working fiddle
BufferGeometry has a fixed number of Vertices, but you can decide how many of them you want to render. The trick is to make use of geometry.attributes.position.needsUpdate = true; and geometry.setDrawRange( 0, nbPointsYouWantToDisplay );
var MAX_POINTS = 1000000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( MAX_POINTS * 3 );
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
Then you can create your cloudpoints and add it to the scene:
//material and scene defined in question
pointCloud = new THREE.Points(geometry, material);
scene.add(pointCloud);
Now I want to add and render 500 new points every 10 milliseconds.
var nbPoints = 500;
var INTERVAL_DURATION = 10;
All I have to do is :
var interval = setInterval(function() {
setPoints();
}, INTERVAL_DURATION)
function setPoints() {
var positions = pointCloud.geometry.attributes.position.array;
var x, y, z, index;
var l = currentPoints + nbPoints;
if(l >= MAX_POINTS) {
clearInterval(interval);
}
for ( var i = currentPoints; i < l; i ++ ) {
x = ( Math.random() - 0.5 ) * 300;
y = ( Math.random() - 0.5 ) * 300;
z = ( Math.random() - 0.5 ) * 300;
positions[ currentPointsIndex ++ ] = x;
positions[ currentPointsIndex ++ ] = y;
positions[ currentPointsIndex ++ ] = z;
}
currentPoints = l;
pointCloud.geometry.attributes.position.needsUpdate = true;
pointCloud.geometry.setDrawRange( 0, currentPoints );
controls.update();
renderer.render(scene, camera);
}
Here's a fiddle with your first setup installed: https://jsfiddle.net/87wg5z27/236/
var scene, renderer, camera;
var cube;
var controls;
init();
animate();
function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 160;
camera.position.z = 400;
camera.lookAt (new THREE.Vector3(0,0,0));
controls = new THREE.OrbitControls (camera, renderer.domElement);
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.computeVertexNormals();
scene.add(pointCloud);
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function animate()
{
controls.update();
requestAnimationFrame ( animate );
renderer.render (scene, camera);
}
Here's one with your second: https://jsfiddle.net/87wg5z27/237/
var scene, renderer, camera;
var cube;
var controls;
init();
animate();
function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 160;
camera.position.z = 400;
camera.lookAt (new THREE.Vector3(0,0,0));
controls = new THREE.OrbitControls (camera, renderer.domElement);
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
scene.add(pointCloud);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.elementsNeedUpdate = true;
tgeometry.computeVertexNormals();
renderer.render(scene, camera);
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function animate()
{
controls.update();
requestAnimationFrame ( animate );
renderer.render (scene, camera);
}
In both cases the point cloud shows for me perfectly fine (release 82). Perhaps there is something else missing where you're neglecting to render something? I notice that your first example doesn't show at what step you call render(). I hope this helps!

THREE.js dynamically add points to a Points geometry does not render

I am using Three.js r83.
I am trying to dynamically add points to a geometry, but the scene never gets updated.
This works :
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.computeVertexNormals();
scene.add(pointCloud);
This doesn't work:
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
scene.add(pointCloud);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.elementsNeedUpdate = true;
tgeometry.computeVertexNormals();
renderer.render(scene, camera);
As you can see, the only difference is the fact that I add scene.add(pointCloud); before adding vertexes.
What do I miss?
You can find a fiddle Thanks to #hectate
To see what I means, just replace
init();
setPoints();
animate();
by
init();
animate();
setPoints();
I am not sure why the THREE.Geometry object doesn't update Points after initial rendering, but I got it working with a THREE.BufferGeometry instead.
Thanks to #Hectate who got a working fiddle for me and #WestLangley who directed me to the hints, here is the working fiddle
BufferGeometry has a fixed number of Vertices, but you can decide how many of them you want to render. The trick is to make use of geometry.attributes.position.needsUpdate = true; and geometry.setDrawRange( 0, nbPointsYouWantToDisplay );
var MAX_POINTS = 1000000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( MAX_POINTS * 3 );
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
Then you can create your cloudpoints and add it to the scene:
//material and scene defined in question
pointCloud = new THREE.Points(geometry, material);
scene.add(pointCloud);
Now I want to add and render 500 new points every 10 milliseconds.
var nbPoints = 500;
var INTERVAL_DURATION = 10;
All I have to do is :
var interval = setInterval(function() {
setPoints();
}, INTERVAL_DURATION)
function setPoints() {
var positions = pointCloud.geometry.attributes.position.array;
var x, y, z, index;
var l = currentPoints + nbPoints;
if(l >= MAX_POINTS) {
clearInterval(interval);
}
for ( var i = currentPoints; i < l; i ++ ) {
x = ( Math.random() - 0.5 ) * 300;
y = ( Math.random() - 0.5 ) * 300;
z = ( Math.random() - 0.5 ) * 300;
positions[ currentPointsIndex ++ ] = x;
positions[ currentPointsIndex ++ ] = y;
positions[ currentPointsIndex ++ ] = z;
}
currentPoints = l;
pointCloud.geometry.attributes.position.needsUpdate = true;
pointCloud.geometry.setDrawRange( 0, currentPoints );
controls.update();
renderer.render(scene, camera);
}
Here's a fiddle with your first setup installed: https://jsfiddle.net/87wg5z27/236/
var scene, renderer, camera;
var cube;
var controls;
init();
animate();
function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 160;
camera.position.z = 400;
camera.lookAt (new THREE.Vector3(0,0,0));
controls = new THREE.OrbitControls (camera, renderer.domElement);
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.computeVertexNormals();
scene.add(pointCloud);
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function animate()
{
controls.update();
requestAnimationFrame ( animate );
renderer.render (scene, camera);
}
Here's one with your second: https://jsfiddle.net/87wg5z27/237/
var scene, renderer, camera;
var cube;
var controls;
init();
animate();
function init()
{
renderer = new THREE.WebGLRenderer( {antialias:true} );
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize (width, height);
document.body.appendChild (renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
camera.position.y = 160;
camera.position.z = 400;
camera.lookAt (new THREE.Vector3(0,0,0));
controls = new THREE.OrbitControls (camera, renderer.domElement);
var tmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 5,
opacity: 1
});
var tgeometry = new THREE.Geometry();
var pointCloud = new THREE.Points(tgeometry, tmaterial);
scene.add(pointCloud);
for(var i = 0; i< 1000; i++) {
x = (Math.random() * 200) - 100;
y = (Math.random() * 200) - 100;
z = (Math.random() * 200) - 100;
tgeometry.vertices.push(new THREE.Vector3(x, y, z));
}
tgeometry.verticesNeedUpdate = true;
tgeometry.elementsNeedUpdate = true;
tgeometry.computeVertexNormals();
renderer.render(scene, camera);
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize ()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function animate()
{
controls.update();
requestAnimationFrame ( animate );
renderer.render (scene, camera);
}
In both cases the point cloud shows for me perfectly fine (release 82). Perhaps there is something else missing where you're neglecting to render something? I notice that your first example doesn't show at what step you call render(). I hope this helps!

Why raycaster.intersectObjects work fine with Geometry built in scene but work bad with model loaded form exterior?

I wanna make a measure tool in three.js,and I use reycaster function to do it.
When I use it with Geometry built in scene,it was fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var geometry = new THREE.SphereGeometry(5, 32, 32);
geometry.scale(10, 10, 10);
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var sphere = new THREE.Mesh(geometry, material);
group.add(sphere);
objects.push(sphere);
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
enter image description here
But When I loaded a model,it doesn't work.As you see result of "alert(intersects.length)" is 0.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ytest</title>
<script src="JSandCSS/three.js"></script>
<script src="JSandCSS/OrbitControls.js"></script>
<script src="JSandCSS/OBJLoader.js"></script>
<script src="JSandCSS/Raycaster.js"></script>
</head>
<body>
<script>
var scene = new THREE.Scene();
var group = new THREE.Group;
var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var objects = [];
var particleMaterial;
particlecount = 0;
var container, stats, titleinfo;
scene.add(group);
var textureLoader = new THREE.TextureLoader();
var mat = new THREE.MeshLambertMaterial({
map: textureLoader.load("model/earth/texture.jpg"),
specularMap: textureLoader.load("model/earth/specular.jpg"),
lightMap: textureLoader.load("model/earth/light.jpg")
});
var loader = new THREE.OBJLoader();
loader.load('model/earth/earth.obj',
function chuanzhi(obj) {
obj.traverse(function(child) {
if(child instanceof THREE.Mesh) {
child.material = mat;
}
});
Mesh = obj;
obj.scale.set(2, 2, 2);
group.add(obj);
objects.push(Mesh);
});
var light = new THREE.PointLight(0xffffff);
light.position.set(300, 400, 200);
light.intensity.set = 0.1;
scene.add(light);
scene.add(new THREE.AmbientLight(0x333333));
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor(0x808080, 0.5);
render();
var controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
animate();
window.addEventListener('resize', handleWindowResize, false);
window.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
event.preventDefault();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects);
var PI2 = Math.PI * 2;
var pointLoader = new THREE.TextureLoader();
particleMaterial = new THREE.SpriteMaterial({
map: pointLoader.load("pic/measurepoint.png"),
});
alert(intersects.length);
if(intersects.length > 0) {
if(particlecount == 0) {
var particle1 = new THREE.Sprite(particleMaterial);
particle1.name = 'particle1';
particle1.position.copy(intersects[0].point);
particle1.scale.x = particle1.scale.y = 5;
scene.add(particle1);
particlecount = 1;
} else {
if(particlecount !== 2) {
var particle2 = new THREE.Sprite(particleMaterial);
particle2.name = 'particle2';
particle2.position.copy(intersects[0].point);
particle2.scale.x = particle2.scale.y = 5;
scene.add(particle2);
particlecount = 2;
a = scene.getObjectByName('particle1');
b = scene.getObjectByName('particle2');
var dis = a.position.distanceTo(b.position);
alert('distance between two point is' + dis);
scene.remove(a);
scene.remove(b);
particlecount = 0;
}
}
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function handleWindowResize() {
HEIGHT = window.innerHeight;
WIDTH = window.innerWidth;
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
}
</script>
</body>
</html>
I wanna know why it happened,and how I can use it correctly.Could you help me ?

Categories

Resources