three.js adding object to scene but not rendering object - javascript

I'm creating a function createCylinder(n, len, rad) that is called from function createScene(). I have checked that the vertices and faces are added and I get no errors. However, the geometry is not rendered. I suppose this has to do with the timing of returning the geometry or returning the mesh and adding it to the scene. That being said, I have tried everything I could think of and found no solution. Can someone please help me figure this out? Thanks in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cylinder</title>
</head>
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="OrbitControls.js"></script>
<style>
body {
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
<body>
<div id="container">
</div>
<div id="msg">
</div>
<script type="text/javascript">
var camera, scene, renderer;
var cameraControls;
var clock = new THREE.Clock();
var isCappedBottom = false;
var isCappedTop = false;
function createCylinder(n, len, rad) {
var geometry = new THREE.Geometry();
var radius = rad;
var length = len;
var yUp = length / 2;
var yDown = -length / 2;
var theta = (2.0 * Math.PI) / n;
for (var i = 0; i < n ; i++) { //runs n + 2 times if we allow redundant vertices
var x = radius * Math.cos(i * theta);
var z = radius * Math.sin(i * theta);
//Top to bottom
var originUp = new THREE.Vector3(x, yUp, z);
var originDown = new THREE.Vector3(x, yDown, z);
geometry.vertices.push(originUp); //0
geometry.vertices.push(originDown); //1
console.log("Vertices " + geometry.vertices.length);
}//end of first for loop
// Draw faces
for (var j = 0; j < 2*n; j+= 2) {
var face1 = new THREE.Face3(j, j + 1, j + 2);
var face2 = new THREE.Face3(j + 1, j + 3, j + 2);
geometry.faces.push(face1);
geometry.faces.push(face2);
console.log("faces " + geometry.faces.length);
}
// return geometry;
//scene.add(geometry);
var material = new THREE.MeshLambertMaterial({color: 0xFF0000, side: THREE.DoubleSide});
var mesh = new THREE.Mesh(geometry, material);
return mesh;
scene.add(mesh);
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x222222);
scene.add(ambientLight);
var light = new THREE.PointLight(0xFFFFFF, 1, 1000);
light.position.set(0, 10, 20);
scene.add(light);
var light2 = new THREE.PointLight(0xFFFFFF, 1, 1000);
light2.position.set(0, -10, -10);
scene.add(light2);
} //End of function
function createScene() {
var cyl = createCylinder(10, 10, 2);
return cyl;
scene.add(cyl);
}
function animate() {
window.requestAnimationFrame(animate);
render();
}
function render() {
var delta = clock.getDelta();
cameraControls.update(delta);
renderer.render(scene, camera);
}
function init() {
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
var canvasRatio = canvasWidth / canvasHeight;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({antialias: true, preserveDrawingBuffer: true});
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.setSize(canvasWidth, canvasHeight);
renderer.setClearColor(0x000000, 1.0);
renderer.shadowMapEnabled = true;
camera = new THREE.PerspectiveCamera( 40, canvasRatio, 1, 1000);
/* camera.position.z = 5;
camera.lookAt(scene.position); */
camera.position.set(0, 0, 12);
camera.lookAt(new THREE.Vector3(0, 0, 0));
cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
}
function addToDOM() {
var container = document.getElementById('container');
var canvas = container.getElementsByTagName('canvas');
if (canvas.length>0) {
container.removeChild(canvas[0]);
}
container.appendChild( renderer.domElement );
}
init();
createScene();
addToDOM();
render();
animate();
</script>
</body>
</html>

In the createCylinder function:
var mesh = new THREE.Mesh(geometry, material);
return mesh; // this line must be the last line in the function
// after return(), the rest of the code is unreacheable
//scene.add(mesh); // this line should be deleted as you add the mesh in the createScene() function
and then the createScene function should be like this:
function createScene() {
var cyl = createCylinder(10, 10, 2);
//return cyl;
scene.add(cyl);
}
jsfiddle example

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>

WireFrame of Json formated geometry in Three.js

I would like to display the wireframe of a parallelepiped defined by vertexes in a Json format using the following Three.js code
var testCube ={
"metadata":{
"version":json['version'],
"type":json['type'],
"uvs":json['n_uvs'],
"normals":json['n_normals'],
"faces":json['n_faces'],
"generator":"io_three",
"vertices":json['n_vertices'],
},
"faces":json['faces'],
"vertices":json['vertices'],
"normals":json['normals'],
"uvs":[],
"name":json['name']}
var loader = new THREE.JSONLoader();
var model = loader.parse( testCube );
meshBox = new THREE.Mesh( model.geometry, model.materials[ 0 ] );
var geo = new THREE.EdgesGeometry( meshBox.geometry );
var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 });
var wireframe = new THREE.LineSegments( geo, mat );
scene.add( wireframe );
however, the above code produce this kind of visualization:
while I would like to produce a visualization where also the internal wireframe is visible as the following:
Question: do you know how I can modify the above Three.js code to produce a full wireframe as displayed in the second picture?
Upadate: using the function WireframeGeometry you have the following plot:
Diagonals appear on each face of the mesh. Do yo know a function that does not produce diagonals?
Thank you very much for your help!
The solution is rough and imperfect, and it's a huge field for improvement and optimization.
You create one geometry and share it between two instances of THREE.LineSegments() for opposing sides of a box.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-15, 10, 10);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.setScalar(10);
scene.add(light);
var box = new THREE.Mesh(new THREE.BoxGeometry(10, 5, 5, 5, 5, 5), new THREE.MeshLambertMaterial({color:"gray"}));
scene.add(box);
var material = new THREE.LineBasicMaterial({
vertexColors: THREE.VertexColors
});
var params = box.geometry.parameters;
var geometryGridXY = Grid(params.width, params.height, params.widthSegments, params.heightSegments, "yellow");
var gridXYFront = new THREE.LineSegments(geometryGridXY, material);
gridXYFront.position.z = params.depth / 2 + 0.001;
box.add(gridXYFront);
var gridXYBack = new THREE.LineSegments(geometryGridXY, material);
gridXYBack.position.z = -params.depth / 2 - 0.001;
box.add(gridXYBack);
var geometryGridYZ = Grid(params.height, params.depth, params.heightSegments, params.depthSegments, "aqua");
var gridYZLeft = new THREE.LineSegments(geometryGridYZ, material);
gridYZLeft.position.x = -params.width / 2 - 0.001;
gridYZLeft.rotation.y = -Math.PI * .5;
box.add(gridYZLeft);
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script>
function Grid(width, height, widthSegments, heightSegments, color) {
width = width || 1;
height = height || 1;
widthSegments = widthSegments || 1;
heightSegments = heightSegments || 1;
color = new THREE.Color(color !== undefined ? color : 0x444444);
var stepWidth = width / widthSegments;
var stepHeight = height / heightSegments;
var halfWidth = width / 2;
var halfHeight = height / 2;
var vertices = [],
colors = [], j = 0;
for (let i = 0, k = -halfHeight; i <= heightSegments; i++, k += stepHeight) {
vertices.push(-halfWidth, k, 0, halfWidth, k, 0);
color.toArray(colors, j); j += 3;
color.toArray(colors, j); j += 3;
}
for (let i = 0, k = -halfWidth; i <= widthSegments; i++, k += stepWidth) {
vertices.push(k, halfHeight, 0, k, -halfHeight, 0);
color.toArray(colors, j); j += 3;
color.toArray(colors, j); j += 3;
}
var geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
return geometry;
}
</script>

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