How to create a simple particle system using THREE.js? - javascript

In the end what I want to do is create simple particle system which is around in a circle with the name of the site in the middle. The particles move around and eventually "die off" and get recreated. I am relatively new to three.js. I have already tried to find a solution but either all of the tutorials are to old and a lot of things have changed or the tutorial doesnt working for what I want to do. Below is what I have so far. It creates the circle with the pixels around in a circle but what I cant get the to do is to get them to move. That is where I need your guys help. Thanks.
var scene = new THREE.Scene();
var VIEW_ANGLE = window.innerWidth / -2,
NEAR = 0.1,
FAR = 1000;
var camera = new THREE.OrthographicCamera( VIEW_ANGLE,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
NEAR,
FAR);
// pull the camera position back
camera.position.z = 300;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth , window.innerHeight );
document.body.appendChild( renderer.domElement );
// Create the particle variables
var particleCount = 1000;
var particles = new THREE.Geometry();
var particle_Material = new THREE.PointsMaterial({
color: 'red',
size: 1
});
var min = -10,
max = 10;
// Create the individual particles
for (var i = 0; i < particleCount; i++) {
var radius = 200;
var random = Math.random();
var variance = Math.random();
var max = 10,
min = -10;
radius += (Math.floor(variance * (max - min + 1)) + min);
var pX = radius * Math.cos(random * (2 * Math.PI)),
pY = radius * Math.sin(random * (2 * Math.PI)),
pZ = Math.random() * 100;
var particle = new THREE.Vector3(
pX,pY,pZ
);
particle.velocity = new THREE.Vector3(
0,
-Math.random(),
0
);
// Add the particle to the geometry
particles.vertices.push(particle);
}
// Create the particle system
var particleSystem = new THREE.Points(
particles,particle_Material
);
particleSystem.sortParticles = true;
// Add the particle system to the scene
scene.add(particleSystem);
// Animation Loop
function render() {
requestAnimationFrame(render);
var pCount = particleCount;
while(pCount--) {
// Get particle
var particle = particles.vertices[pCount];
console.log(particle);
particle.y -= Math.random(5) * 10;
console.log(particle);
}
renderer.render(scene,camera);
}
render();

You can use....
particleSystem.rotateZ(0.1);
....in your render loop. 0.1 is the amount you'd like your particle system to rotate per frame.
Hope that helps!

Related

Why is threeJS applyMatrix causing my console to go crazy and crash my browser?

This is based off a codepen that I am working on and I simplified the code to work with the specific part I need. I haven't worked with applyMatrix and Matrix4 before. For some reason the info from the part using these functions are showing up in my console and causing my browser to crash. I don't completely understand what is going on. I can guess that the values are being reassigned nonstop but I don't see a resolution to it in the codepen even though this issue isn't in it. Here is my code and the link to the codepen for reference.
https://codepen.io/Mamboleoo/pen/Bppdda?editors=0010
This codepen is out of my league and I am trying to get a better grasp of it.
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
renderer.setClearColor(0x000000);
const spotLight = new THREE.SpotLight(0xFFFFFF);
scene.add(spotLight);
spotLight.position.set(0, 0, 100);
spotLight.castShadow = true;
spotLight.angle = 0.2;
spotLight.intensity = 0.2;
camera.position.set(0.27, 0, 500);
//Black center
var geom = new THREE.SphereGeometry(100, 32, 32);
var mat = new THREE.MeshPhongMaterial({
color: 0x000000
});
var core = new THREE.Mesh(geom, mat);
scene.add(core);
var geom = new THREE.SphereBufferGeometry(1, 15, 15);
var mat = new THREE.MeshBasicMaterial({
color: 0xffffff
});
var atoms = new THREE.Object3D();
scene.add(atoms);
for (var i = 0; i < 150; i++) {
var nucleus = new THREE.Mesh(geom, mat);
var size = Math.random() * 6 + 1.5;
nucleus.speedX = (Math.random() - 0.5) * 0.08;
nucleus.speedY = (Math.random() - 0.5) * 0.08;
nucleus.speedZ = (Math.random() - 0.5) * 0.08;
nucleus.applyMatrix(new THREE.Matrix4().makeScale(size, size, size));
nucleus.applyMatrix(new THREE.Matrix4().makeTranslation(0, 100 + Math.random() * 10, 0));
nucleus.applyMatrix(new THREE.Matrix4().makeRotationX(Math.random() * (Math.PI * 2)));
nucleus.applyMatrix(new THREE.Matrix4().makeRotationY(Math.random() * (Math.PI * 2)));
nucleus.applyMatrix(new THREE.Matrix4().makeRotationZ(Math.random() * (Math.PI * 2)));
atoms.add(nucleus);
}
function updateNucleus(a) {
for (var i = 0; i < atoms.children.length; i++) {
var part = atoms.children[i];
part.applyMatrix(new THREE.Matrix4().makeRotationX(part.speedX));
part.applyMatrix(new THREE.Matrix4().makeRotationY(part.speedY));
part.applyMatrix(new THREE.Matrix4().makeRotationZ(part.speedZ));
}
}
//Create scene
var necks = [];
var cubesObject = new THREE.Object3D();
scene.add(cubesObject);
function animate(a) {
requestAnimationFrame( animate );
updateNucleus(a);
renderer.render(scene,camera);
};
animate();
window.addEventListener('resize', function(){
camera.aspect = window.innerWidth / this.window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
})
part.applyMatrix(new THREE.Matrix4().makeRotationX(part.speedX));
The codepen uses an old version of three.js (r79). Since certain parts of the API have been renamed, the browser reports deprecation warnings every frame. With the latest version r138, the new code should look like so:
part.applyMatrix4(new THREE.Matrix4().makeRotationX(part.speedX));
Besides, it's recommended that you don't create instances of Matrix4 and other classes within the animation loop. Create the objects once outside of your loop and reuse them.
const _matrix = new THREE.Matrix4();
function updateNucleus(a) {
for (var i = 0; i < atoms.children.length; i++) {
var part = atoms.children[i];
part.applyMatrix4(_matrix.makeRotationX(part.speedX));
part.applyMatrix4(_matrix.makeRotationY(part.speedY));
part.applyMatrix4(_matrix.makeRotationZ(part.speedZ));
}
}

How can I improve the performance of a three.js script?

I have a really nice js animation that i would like to use as a website background. Unfortunately it seems to be very intensive in CPU/GPU usage. The animation itself runs quite smooth, but my GPU is at 100%. other animations on the website don't run smooth at all and seem to lag.
I already looked at other Stackoverflow posts concerning boosting the performance of three.js scripts, but the ideas didn't work for me yet. For example I reduced the calls from 600 down to 200 by reducing the "city" objects in order to improve performance, but GPU is still at 100%.
I updated three.js to the latest version and so on. Nothing worked so far. I am quite new to three.js and JS so please don't be too harsh with me. Also I didn't really know which parts of the code will really boost performance, so I included the whole thing - even though it is very long. I hope the comments help to skip to the right parts.
Thanks in advance for your help!
// Three JS Template
//----------------------------------------------------------------- BASIC parameters
var renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight );
if (window.innerWidth > 800) {
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.needsUpdate = true;
};
document.getElementById('animated-bg').appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
};
var camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 1, 500 );
camera.position.set(0, 2, 14);
var scene = new THREE.Scene();
var city = new THREE.Object3D();
var smoke = new THREE.Object3D();
var town = new THREE.Object3D();
var createCarPos = true;
var uSpeed = 0.001;
//----------------------------------------------------------------- FOG background
var setcolor = 0x862834;
scene.background = new THREE.Color(setcolor);
scene.fog = new THREE.Fog(setcolor, 10, 16);
//----------------------------------------------------------------- RANDOM Function
function mathRandom(num = 8) {
var numValue = - Math.random() * num + Math.random() * num;
return numValue;
};
//----------------------------------------------------------------- CHANGE bluilding colors
var setTintNum = true;
function setTintColor() {
if (setTintNum) {
setTintNum = false;
var setColor = 0x000000;
} else {
setTintNum = true;
var setColor = 0x000000;
};
//setColor = 0x222222;
return setColor;
};
//----------------------------------------------------------------- CREATE City
function init() {
var segments = 2;
for (var i = 1; i<50; i++) {
var geometry = new THREE.CubeGeometry(1,0,0,segments,segments,segments);
var material = new THREE.MeshStandardMaterial({
color:setTintColor(),
wireframe:false,
shading: THREE.SmoothShading,
side:THREE.DoubleSide});
var wmaterial = new THREE.MeshLambertMaterial({
color:0xFFFFFF,
wireframe:true,
transparent:true,
opacity: 0.03,
side:THREE.DoubleSide});
var cube = new THREE.Mesh(geometry, material);
var wire = new THREE.Mesh(geometry, wmaterial);
var floor = new THREE.Mesh(geometry, material);
var wfloor = new THREE.Mesh(geometry, wmaterial);
cube.add(wfloor);
cube.castShadow = true;
cube.receiveShadow = true;
cube.rotationValue = 0.1+Math.abs(mathRandom(8));
floor.scale.y = 0.05;//+mathRandom(0.5);
cube.scale.y = 0.1+Math.abs(mathRandom(8));
var cubeWidth = 0.9;
cube.scale.x = cube.scale.z = cubeWidth+mathRandom(1-cubeWidth);
cube.position.x = Math.round(mathRandom());
cube.position.z = Math.round(mathRandom());
floor.position.set(cube.position.x, 0/*floor.scale.y / 2*/, cube.position.z)
town.add(floor);
town.add(cube);
};
//----------------------------------------------------------------- Particular
var gmaterial = new THREE.MeshToonMaterial({color:0xFFFF00, side:THREE.DoubleSide});
var gparticular = new THREE.CircleGeometry(0.01, 3);
var aparticular = 5;
for (var h = 1; h<300; h++) {
var particular = new THREE.Mesh(gparticular, gmaterial);
particular.position.set(mathRandom(aparticular), mathRandom(aparticular),mathRandom(aparticular));
particular.rotation.set(mathRandom(),mathRandom(),mathRandom());
smoke.add(particular);
};
var pmaterial = new THREE.MeshPhongMaterial({
color:0x000000,
side:THREE.DoubleSide,
roughness: 10,
metalness: 0.6,
opacity:0.9,
transparent:true});
var pgeometry = new THREE.PlaneGeometry(60,60);
var pelement = new THREE.Mesh(pgeometry, pmaterial);
pelement.rotation.x = -90 * Math.PI / 180;
pelement.position.y = -0.001;
pelement.receiveShadow = true;
city.add(pelement);
};
//----------------------------------------------------------------- MOUSE function
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2(), INTERSECTED;
var intersected;
function onMouseMove(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
};
function onDocumentTouchStart( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouse.x = event.touches[ 0 ].pageX - window.innerWidth / 2;
mouse.y = event.touches[ 0 ].pageY - window.innerHeight / 2;
};
};
function onDocumentTouchMove( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouse.x = event.touches[ 0 ].pageX - window.innerWidth / 2;
mouse.y = event.touches[ 0 ].pageY - window.innerHeight / 2;
}
}
window.addEventListener('mousemove', onMouseMove, false);
window.addEventListener('touchstart', onDocumentTouchStart, false );
window.addEventListener('touchmove', onDocumentTouchMove, false );
//----------------------------------------------------------------- Lights
var ambientLight = new THREE.AmbientLight(0xFFFFFF, 4);
var lightFront = new THREE.SpotLight(0xFFFFFF, 20, 10);
var lightBack = new THREE.PointLight(0xFFFFFF, 0.5);
var spotLightHelper = new THREE.SpotLightHelper( lightFront );
lightFront.rotation.x = 45 * Math.PI / 180;
lightFront.rotation.z = -45 * Math.PI / 180;
lightFront.position.set(5, 5, 5);
lightFront.castShadow = true;
lightFront.shadow.mapSize.width = 6000;
lightFront.shadow.mapSize.height = lightFront.shadow.mapSize.width;
lightFront.penumbra = 0.1;
lightBack.position.set(0,6,0);
smoke.position.y = 2;
scene.add(ambientLight);
city.add(lightFront);
scene.add(lightBack);
scene.add(city);
city.add(smoke);
city.add(town);
//----------------------------------------------------------------- GRID Helper
var gridHelper = new THREE.GridHelper( 60, 120, 0xFF0000, 0x000000);
city.add( gridHelper );
//----------------------------------------------------------------- CAR world
var generateCar = function() {
}
//----------------------------------------------------------------- LINES world
var createCars = function(cScale = 2, cPos = 20, cColor = 0xFFFF00) {
var cMat = new THREE.MeshToonMaterial({color:cColor, side:THREE.DoubleSide});
var cGeo = new THREE.CubeGeometry(1, cScale/40, cScale/40);
var cElem = new THREE.Mesh(cGeo, cMat);
var cAmp = 3;
if (createCarPos) {
createCarPos = false;
cElem.position.x = -cPos;
cElem.position.z = (mathRandom(cAmp));
TweenMax.to(cElem.position, 3, {x:cPos, repeat:-1, yoyo:true, delay:mathRandom(3)});
} else {
createCarPos = true;
cElem.position.x = (mathRandom(cAmp));
cElem.position.z = -cPos;
cElem.rotation.y = 90 * Math.PI / 180;
TweenMax.to(cElem.position, 5, {z:cPos, repeat:-1, yoyo:true, delay:mathRandom(3), ease:Power1.easeInOut});
};
cElem.receiveShadow = true;
cElem.castShadow = true;
cElem.position.y = Math.abs(mathRandom(5));
city.add(cElem);
};
var generateLines = function() {
for (var i = 0; i<60; i++) {
createCars(0.1, 20);
};
};
//----------------------------------------------------------------- CAMERA position
var cameraSet = function() {
createCars(0.1, 20, 0xFFFFFF);
};
//----------------------------------------------------------------- ANIMATE
var animate = function() {
var time = Date.now() * 0.00005;
requestAnimationFrame(animate);
city.rotation.y -= ((mouse.x * 8) - camera.rotation.y) * uSpeed;
city.rotation.x -= (-(mouse.y * 2) - camera.rotation.x) * uSpeed;
if (city.rotation.x < -0.05) city.rotation.x = -0.05;
else if (city.rotation.x>1) city.rotation.x = 1;
var cityRotation = Math.sin(Date.now() / 5000) * 13;
for ( let i = 0, l = town.children.length; i < l; i ++ ) {
var object = town.children[ i ];
}
smoke.rotation.y += 0.01;
smoke.rotation.x += 0.01;
camera.lookAt(city.position);
renderer.render( scene, camera );
}
//----------------------------------------------------------------- START functions
generateLines();
init();
animate();
There are many things you could do.
For starters, you want to keep your Mesh number low to reduce drawcalls. This means that you shouldn't create one mesh for cube and one for floor. If they share the same material, just create 2 separate geometries, then merge them with BufferGeometryUtils.mergeBufferGeometries.
If you have 50 buildings with the same material, you should also merge them so they all draw at once.
MeshStandardMaterial is pretty expensive to render, so since you're not using environment reflections, you should consider Phong or Lambert materials instead, which are much less resource-intensive.
Shadows basically double your drawcalls per frame because it has to first calculate all shadow-casting geometries. If your buildings aren't going to move, set lightFront.shadow.autoUpdate = false after the first frame.
Don't create a new circular Mesh for each particle. That's 300 meshes! Instead, use THREE.Points, which has the capacity of drawing thousands of particles on a single drawcall, saving you tons of render time, as in this example.
Don't set your renderer's pixelRatio to anything above 1, if you do. That'd just kill your performance.
I don't have time to get into the car creation, but the same principle applies: try to reduce your drawcalls!

Three.js OrbitControls with azimuth close to +/-180 degrees

I have a situation where I use an OrbitControls to have a limited view in a room/space. The OrbitControls gets min/max values for azimuth and polar angles to control the view.
The OrbitControls' target is close by the camera to achieve the correct view, compare to the "panorama / cube" example (https://threejs.org/examples/?q=cube#webgl_panorama_cube).
In one situation this works fine. In an other situation this does not work. The reason is that because of the placement of objects, the starting azimuth is -179.999 degrees.
I have not found a way to tell the orbitcontrol to have the azimuth between -179.999 +/- 20 degrees.
I have experimented a little with the algorithm of #Αλέκος (Is angle in between two angles) and it looks like I can calculate the correct angles (not fully implemented). For that I would have set an azimuth and a delta in stead of min/max (and change the OrbitControls code).
Any suggestions for an easier solution? Thanks!
Test code:
var scene = new THREE.Scene();
var orbitControls;
var camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var material = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: THREE.FaceColors
});
var geometry = new THREE.BoxGeometry(1, 1, 1);
// colors
red = new THREE.Color(1, 0, 0);
green = new THREE.Color(0, 1, 0);
blue = new THREE.Color(0, 0, 1);
var colors = [red, green, blue];
console.log("FACES", geometry.faces.length)
for (var i = 0; i < 3; i++) {
geometry.faces[4 * i].color = colors[i];
geometry.faces[4 * i + 1].color = colors[i];
geometry.faces[4 * i + 2].color = colors[i];
geometry.faces[4 * i + 3].color = colors[i];
}
geometry.faces[0].color = new THREE.Color(1, 1, 1);
geometry.faces[4].color = new THREE.Color(1, 1, 1);
geometry.faces[8].color = new THREE.Color(1, 1, 1);
var cube = new THREE.Mesh(geometry, material);
cube.position.x = 0;
cube.position.y = 4;
cube.position.z = 44;
console.log("CUBE", cube.position);
var cubeAxis = new THREE.AxesHelper(20);
cube.add(cubeAxis);
scene.add(cube);
camera.position.x = 0.8;
camera.position.y = 4.5;
camera.position.z = 33;
orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.enablePan = false;
orbitControls.enableZoom = false;
orbitControls.minPolarAngle = (90 - 10) * Math.PI / 180;
orbitControls.maxPolarAngle = (90 + 10) * Math.PI / 180;
// These values do not work:
orbitControls.maxAzimuthAngle = 200 * Math.PI / 180;
orbitControls.minAzimuthAngle = 160 * Math.PI / 180;
orbitControls.target.x = 0.8;
orbitControls.target.y = 4.5;
orbitControls.target.z = 33.1;
orbitControls.enabled = true;
var animate = function () {
requestAnimationFrame(animate);
if (orbitControls) {
orbitControls.update();
}
renderer.render(scene, camera);
// console.log("orbitControls", "azi", orbitControls.getAzimuthalAngle() * 180 / Math.PI);
};
animate();

Point sprite rendering issues with three.js

I'm currently working an a project which will visualize data on browser by rendering excessive amounts of animated stroked circles. I started evaluating 3D libraries and ended up trying to create a proof of concept application with three.js. It is capable of animating and rendering up to 150 000 point sprites at 60 fps on my 1440p monitor. Everything looks great until you start looking at the details. It has two rendering issues:
It creates strange horizontal lines even when you turn animation off
https://imgur.com/a/3Ugd0
When you turn the camera, transparent areas of overlapping point sprites will show the background instead of underlying point sprites
https://imgur.com/a/NcIwX
Here is the proof of concept application: https://jsfiddle.net/tcpvfbsd/1/
var renderer, scene, camera, controls;
var points;
var stats;
var controls;
var worldWidth = 200;
var worldRadius = worldWidth / 2;
var patchSize = 10;
var pointsAmount = 100000;
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
scene.background = new THREE.Color(0x1d252d);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.set(0, worldWidth * 1.5, 0);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.minDistance = 100;
controls.maxDistance = 1100;
scene.add(new THREE.GridHelper(2 * worldRadius, 2 * worldWidth / patchSize, 0x444444, 0x444444));
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array(pointsAmount * 3);
var rotations = new Float32Array(pointsAmount * 1);
for (var i = 0; i < pointsAmount; i++) {
positions[i] = 0;
positions[i + 1] = 0;
positions[i + 2] = 0;
rotations[i] = 2 * Math.PI * Math.random();
}
controls = new function() {
this.speed = 10;
this.amount = 10;
};
var gui = new dat.GUI();
gui.add(controls, 'speed', 0, 100);
//gui.add(controls, 'amount', 0, 10000).step(1);;
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('rotation', new THREE.BufferAttribute(rotations, 1));
var loader = new THREE.TextureLoader();
loader.load('//i.imgur.com/AmQQnZc.png', function(texture) {
var material = new THREE.PointsMaterial({
size: 5,
transparent: true,
map: texture
});
points = new THREE.Points(geometry, material);
scene.add(points);
stats = new Stats();
document.body.appendChild(stats.dom);
animate();
});
}
function animate() {
requestAnimationFrame(animate);
var position = points.geometry.attributes.position;
var count = position.count;
var rotation = points.geometry.attributes.rotation;
var speed = patchSize * controls.speed / 100;
if (speed > 0) {
for (var i = 0; i < count; i++) {
var wiggle = Math.random() > 0.9 ? THREE.Math.randFloat(-0.1, 0.1) : 0;
var theta = rotation.getX(i) + wiggle;
let dx = speed * Math.cos(theta);
let dz = speed * Math.sin(theta);
var x0 = position.getX(i);
var z0 = position.getZ(i);
var x = THREE.Math.clamp(x0 + dx, -worldRadius, worldRadius);
var z = THREE.Math.clamp(z0 + dz, -worldRadius, worldRadius);
if (Math.abs(x) === worldRadius) dx = -dx;
if (Math.abs(z) === worldRadius) dz = -dz;
position.setX(i, x);
position.setZ(i, z);
position.setY(i, 1);
rotation.setX(i, Math.atan2(dz, dx));
}
}
position.needsUpdate = true;
stats.update();
renderer.render(scene, camera);
}
init();
Best way to see the issues is to wait couple of seconds for the point sprites to spread across to area, use speed control on top right corner to pause animation and the use mouse's left button to turn and rotate the camera.
Using alphaTest with value 0.5 clipped the corners off the circles without affecting the rendering of other circles
Setting transparent value to false removed the buggy fade effect which came after setting alphaTest to 0.5
Adding fading to the texture itself made the circles' borders smooth even thought the transparent setting which caused the fade effect was disabled
Randomizing the position on y axis by 0.01 units removed the strange horizontal lines

How to place 3d box inside another 3d box using three.js?

I am working on cargo management project. I need to render the packing order in 3d image, I am beginner to use THREE.js.
I have the positions (x,y,z axis) and size of the objects inside the container and container size. Now I need to render in 3d image.
I learned to render the container and objects separately, but don't know how to place the objects inside the container.
Please help me out to learn how to do this.
Here I tried something out like this.
init();
animate();
function init() {
var aspect = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 1, 6000);
camera.position.x = radius * Math.sin(THREE.Math.degToRad(theta));
camera.position.y = radius * Math.sin(THREE.Math.degToRad(theta));
camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta));
scene.add(camera);
var geometry = new THREE.BoxBufferGeometry(2000, 2150, 5600, 1, 1, 1);
var material = new THREE.MeshPhongMaterial({ color: 0x000000, wireframe:true });
container = new THREE.Mesh(geometry, material);
container.position.x = 100;
container.position.y = 100;
container.position.z = 100;
container.scale.x = 2000;
container.scale.y = 2150;
container.scale.z = 5600;
scene.add(container);
var geometry = new THREE.BoxBufferGeometry(20, 20, 20);
for (var i = 0; i < 20; i++) {
var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff }));
object.position.x = Math.random() * 800 - 400;
object.position.y = Math.random() * 800 - 400;
object.position.z = Math.random() * 800 - 400;
object.scale.x = Math.random() + 5;
object.scale.y = Math.random() + 5;
object.scale.z = Math.random() + 5;
scene.add(object);
container.add(object);
}
}
function animate()
{
renderer.render(scene, camera);
}
But it shows no result and no error.
You have to add the objects as the child of the container and then set the position of the objects.
// first add the container in the scene
var geometry = new THREE.BoxGeometry(container_width, container_height, container_depth);
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var container = new THREE.Mesh(geometry, material);
scene.add(container);
// then add objects as the child of container
var geometry_obj = new THREE.BoxGeometry(object_width, object_height, object_depth);
var material_obj = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var object = new THREE.Mesh(geometry_obj, material_obj);
// you can set the object's position in the container
object.position.set(object_position.x, object_position.y, object_position.z)
container.add(object);

Categories

Resources