I read a Chinese book about WebGL. I run the particle system example of the book with firefox, I meet a problem my particle cannot move.
I put my source code and resource in the website:
https://onedrive.live.com/redir?resid=FBEB6373D9321A7F!649236&authkey=!AA4upPPcARcAvso&ithint=file%2czip
Console Logs on the browser are:
"THREE.WebGLRenderer" "75"
three.min.js:631:0 "THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead."
three.min.js:791:67 "THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial."
three.min.js:777:230 "THREE.ParticleSystem has been renamed to THREE.Points."
three.min.js:769:197 "THREE.WebGLRenderer: image is not power of two (109x109). Resized to 128x128"
Here is partial code of the html file:
function updateParticles(){
var particleNum = particleSystem.geometry.vertices.length;
for(var i=0; i<particleNum; i++){
particle = particleSystem.geometry.vertices[i];
particle.z += 5;
if(particle.z>1000){
particle.z-=2000;
}
}
}
function animate() {
requestAnimationFrame(animate);
updateParticles();
renderer.render(scene, camera);
}
Could someone help to solve this problem? Thanks!
I think you maybe using an old version of three.js and it doesn't work with the particle system. Here is a sample that is pretty close to what you are doing. When I run this sample locally it works, then replacing by the three.min.js from your project it stops working. You can grab the three.js version used by this sample there.
// #see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// set the scene size
var WIDTH = 400,
HEIGHT = 300;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.Camera( VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
var scene = new THREE.Scene();
// the camera starts at 0,0,0 so pull it back
camera.position.z = 300;
// start the renderer - set the clear colour
// to a full black
renderer.setClearColor(new THREE.Color(0, 1));
renderer.setSize(WIDTH, HEIGHT);
// attach the render-supplied DOM element
$container.append(renderer.domElement);
// create the particle variables
var particleCount = 1800,
particles = new THREE.Geometry(),
pMaterial = new THREE.ParticleBasicMaterial({
color: 0xFFFFFF,
size: 20,
map: THREE.ImageUtils.loadTexture(
"./Images/icon_ch.png"
),
blending: THREE.AdditiveBlending,
transparent: true
});
// now create the individual particles
for(var p = 0; p < particleCount; p++) {
// create a particle with random
// position values, -250 -> 250
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vertex(
new THREE.Vector3(pX, pY, pZ)
);
// create a velocity vector
particle.velocity = new THREE.Vector3(
0, // x
-Math.random(), // y
0); // z
// add it to the geometry
particles.vertices.push(particle);
}
// create the particle system
var particleSystem = new THREE.ParticleSystem(
particles,
pMaterial);
particleSystem.sortParticles = true;
// add it to the scene
scene.addChild(particleSystem);
// animation loop
function update() {
// add some rotation to the system
particleSystem.rotation.y += 0.01;
var pCount = particleCount;
while(pCount--) {
// get the particle
var particle = particles.vertices[pCount];
// check if we need to reset
if(particle.position.y < -200) {
particle.position.y = 200;
particle.velocity.y = 0;
}
// update the velocity
particle.velocity.y -= Math.random() * .1;
// and the position
particle.position.addSelf(
particle.velocity);
}
// flag to the particle system that we've
// changed its vertices. This is the
// dirty little secret.
particleSystem.geometry.__dirtyVertices = true;
renderer.render(scene, camera);
// set up the next call
requestAnimFrame(update);
}
requestAnimFrame(update);
Related
three.js beginner here! I'm working through several tutorials to learn how to animate 3D objects with three.js, so parts of the code here will seem familiar.
What I'd like to do: find a way to change the scale of each object over a period of time (3 to 5 seconds) in a loop. Ideally, these objects will change in size (and, possibly, shape).
What I have:
var Decoration = function() {
// Run the Group constructor with the given arguments
THREE.Group.apply(this, arguments);
this.rotationSpeed = Math.random() * 0.01 + .001 + .001;
this.rotationPosition = Math.random() * 0.01 + .001 + .001;
this.scale = Math.random() * 0.21 + .051 + .021;
this.rotation.x += 0.01;
this.rotation.y += 0.02;
this.scale.x += 1;
this.scale.y += 1;
this.scale.z = 1;
// A random color assignment
var colors = ['#ff0051', '#f56762','#a53c6c','#f19fa0','#72bdbf','#47689b'];
// The main bauble is an Octahedron
var bauble = new THREE.Mesh(
addNoise(new THREE.OctahedronGeometry(15,0), 0),
new THREE.MeshStandardMaterial( {
color: colors[Math.floor(Math.random()*colors.length)],
shading: THREE.FlatShading ,
metalness: 0,
roughness: 0.8,
refractionRatio: 0.25
} )
);
bauble.castShadow = true;
bauble.receiveShadow = true;
bauble.rotateZ(Math.random()*Math.PI*2);
bauble.rotateY(Math.random()*Math.PI*2);
this.add(bauble);
};
Decoration.prototype = Object.create(THREE.Group.prototype);
Decoration.prototype.constructor = Decoration;
Decoration.prototype.updatePosition = function() {
this.rotationPosition += this.rotationSpeed;
this.rotation.y = (Math.sin(this.rotationPosition));
};
var clock = new THREE.Clock();
// Create a scene which will hold all our meshes to be rendered
var scene = new THREE.Scene();
// Create and position a camera
var camera = new THREE.PerspectiveCamera(
60, // Field of view
window.innerWidth/window.innerHeight, // Aspect ratio
0.1, // Near clipping pane
1000 // Far clipping pane
);
// Reposition the camera
camera.position.set(0,30,50);
// Point the camera at a given coordinate
camera.lookAt(new THREE.Vector3(0,15,0))
// Create a renderer
var renderer = new THREE.WebGLRenderer({ antialias: true });
// Size should be the same as the window
renderer.setSize( window.innerWidth, window.innerHeight );
// Set a near white clear color (default is black)
renderer.setClearColor( 0xfff6e6 );
// Append to the document
document.body.appendChild( renderer.domElement );
var decorations = [];
// Add some new instances of our decoration
var decoration1 = new Decoration();
decoration1.position.y += 10;
scene.add(decoration1);
decorations.push(decoration1);
var decoration2 = new Decoration();
decoration2.position.set(20,15,-10);
decoration2.scale.set(.8,.8,.8);
scene.add(decoration2);
decorations.push(decoration2);
var decoration3 = new Decoration();
decoration3.position.set(20,10,-10);
scene.add(decoration3);
decorations.push(decoration3);
var decoration4 = new Decoration();
decoration3.position.set(20,10,-10);
scene.add(decoration4);
decorations.push(decoration4);
// Render the scene/camera combnation
renderer.render(scene, camera);
requestAnimationFrame(render);
function render() {
controls.update();
var t = clock.getElapsedTime();
if (t >= 3.0)
{
clock = new THREE.Clock();
this.scale.set(1,1,1);
}
else
{
this.scale.x = 1-(t/3.0);
this.scale.y = 1-(t/3.0);
this.scale.z = 1-(t/3.0);
}
// Update the decoration positions
for(var d = 0; d < decorations.length; d++) {
decorations[d].updatePosition();
}
// Render the scene/camera combnation
renderer.render(scene, camera);
// Repeat
requestAnimationFrame(render);
}
Any help here would be greatly appreciated!! Thank you :)
The animation/render for any decoration element you have set up happens in the render function. By adding your sought after transitions to the decoration elements in your render function, you can apply it to multiple variables.
Try this:
First, declare your clock variable:
var clock = new THREE.Clock();
Then, update your render function to:
function render() {
for(var d = 0; d < decorations.length; d++) {
decorations[d].rotation.x += 0.01;
decorations[d].rotation.y += 0.01;
}
var t = clock.getElapsedTime();
if (t >= 3.0)
{
clock = new THREE.Clock();
// Update the decoration positions
for(var d = 0; d < decorations.length; d++) {
decorations[d].scale.set(1,1,1);
}
}
else
{
// Update the decoration positions
for(var d = 0; d < decorations.length; d++) {
decorations[d].scale.x = 1-(t/3.0);
decorations[d].scale.y = 1-(t/3.0);
decorations[d].scale.z = 1-(t/3.0);
}
}
// Render the scene/camera combnation
renderer.render(scene, camera);
// Repeat
requestAnimationFrame(render);
}
The short version: How can one make a camera follow an object controlled by physics within a Three.js scene?
The long version: I'm working on a Three.js scene in which the W,A,S,D keys move a sphere along a plane. So far, however, I haven't figured out how to make the camera follow behind the sphere.
In the example below, the camera follows the sphere perfectly if one only presses the W key. However, if one presses A or D, the sphere starts to turn, and the camera is no longer behind the ball. If the sphere starts to turn, I want the camera to turn with it, so the camera is always following just behind the sphere, and is always a constant distance from the sphere. As users continue to press W, the ball will continue rolling forward relative to the camera.
In a previous scene [demo], I was able to implement this behavior by creating the sphere, adding that sphere to a group, then using the following bit of code each frame:
var relativeCameraOffset = new THREE.Vector3(0,50,200);
var cameraOffset = relativeCameraOffset.applyMatrix4(sphereGroup.matrixWorld);
camera.position.x = cameraOffset.x;
camera.position.y = cameraOffset.y;
camera.position.z = cameraOffset.z;
camera.lookAt(sphereGroup.position);
The key in the demo above was to rotate the sphere while keeping the sphereGroup unrotated, so I could compute the cameraOffset on the un-rotated sphereGroup.
In the demo below, the sphere's position is controlled by the Cannon.js physics library, which translates and rotates the sphere as forces are applied to the body. Does anyone know how I can make the camera follow behind the sphere in the scene below?
/**
* Generate a scene object with a background color
**/
function getScene() {
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
return scene;
}
/**
* Generate the camera to be used in the scene. Camera args:
* [0] field of view: identifies the portion of the scene
* visible at any time (in degrees)
* [1] aspect ratio: identifies the aspect ratio of the
* scene in width/height
* [2] near clipping plane: objects closer than the near
* clipping plane are culled from the scene
* [3] far clipping plane: objects farther than the far
* clipping plane are culled from the scene
**/
function getCamera() {
var aspectRatio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 10000);
camera.position.set(0, 2000, -5000);
camera.lookAt(scene.position);
return camera;
}
/**
* Generate the light to be used in the scene. Light args:
* [0]: Hexadecimal color of the light
* [1]: Numeric value of the light's strength/intensity
* [2]: The distance from the light where the intensity is 0
* #param {obj} scene: the current scene object
**/
function getLight(scene) {
var light = new THREE.PointLight( 0xffffff, 0.6, 0, 0 )
light.position.set( -2000, 1000, -2100 );
scene.add( light );
var light = new THREE.PointLight( 0xffffff, 0.15, 0, 0 )
light.position.set( -190, 275, -1801 );
light.castShadow = true;
scene.add( light );
// create some ambient light for the scene
var ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambientLight);
return light;
}
/**
* Generate the renderer to be used in the scene
**/
function getRenderer() {
// Create the canvas with a renderer
var renderer = new THREE.WebGLRenderer({antialias: true});
// Add support for retina displays
renderer.setPixelRatio(window.devicePixelRatio);
// Specify the size of the canvas
renderer.setSize(window.innerWidth, window.innerHeight);
// Enable shadows
renderer.shadowMap.enabled = true;
// Specify the shadow type; default = THREE.PCFShadowMap
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Add the canvas to the DOM
document.body.appendChild(renderer.domElement);
return renderer;
}
/**
* Generate the controls to be used in the scene
* #param {obj} camera: the three.js camera for the scene
* #param {obj} renderer: the three.js renderer for the scene
**/
function getControls(camera, renderer) {
var controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.zoomSpeed = 0.4;
controls.panSpeed = 0.4;
return controls;
}
/**
* Get stats
**/
function getStats() {
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
stats.domElement.style.right = '0px';
document.body.appendChild( stats.domElement );
return stats;
}
/**
* Get grass
**/
function getGrass() {
var texture = loader.load('http://4.bp.blogspot.com/-JiJEc7lH1Is/UHJs3kn261I/AAAAAAAADYA/gQRAxHK2q_w/s1600/tileable_old_school_video_game_grass.jpg');
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(10, 10);
var material = new THREE.MeshLambertMaterial({
map: texture,
side: THREE.DoubleSide,
});
return material;
}
function getPlanes(scene, loader) {
var planes = [];
var material = getGrass();
[ [4000, 2000, 0, 0, -1000, 0] ].map(function(p) {
var geometry = new THREE.PlaneGeometry(p[0], p[1]);
var plane = new THREE.Mesh(geometry, material);
plane.position.x = p[2];
plane.position.y = p[3];
plane.position.z = p[4];
plane.rotation.y = p[5];
plane.rotation.x = Math.PI / 2;
plane.receiveShadow = true;
planes.push(plane);
scene.add(plane);
})
return planes;
}
/**
* Add background
**/
function getBackground(scene, loader) {
var imagePrefix = 'sky-parts/';
var directions = ['right', 'left', 'top', 'bottom', 'front', 'back'];
var imageSuffix = '.bmp';
var geometry = new THREE.BoxGeometry( 4000, 4000, 4000 );
// Add each of the images for the background cube
var materialArray = [];
for (var i = 0; i < 6; i++)
materialArray.push( new THREE.MeshBasicMaterial({
//map: loader.load(imagePrefix + directions[i] + imageSuffix),
color: 0xff0000,
side: THREE.BackSide
}));
var sky = new THREE.Mesh( geometry, materialArray );
scene.add(sky);
return sky;
}
/**
* Add a character
**/
function getSphere(scene) {
var geometry = new THREE.SphereGeometry( 30, 12, 9 );
var material = new THREE.MeshPhongMaterial({
color: 0xd0901d,
emissive: 0xaa0000,
side: THREE.DoubleSide,
flatShading: true
});
var sphere = new THREE.Mesh( geometry, material );
// allow the sphere to cast a shadow
sphere.castShadow = true;
sphere.receiveShadow = false;
// create a group for translations and rotations
var sphereGroup = new THREE.Group();
sphereGroup.add(sphere)
sphereGroup.castShadow = true;
sphereGroup.receiveShadow = false;
scene.add(sphereGroup);
return [sphere, sphereGroup];
}
/**
* Initialize physics engine
**/
function getPhysics() {
world = new CANNON.World();
world.gravity.set(0, -400, 0); // earth = -9.82 m/s
world.broadphase = new CANNON.NaiveBroadphase();
world.broadphase.useBoundingBoxes = true;
var solver = new CANNON.GSSolver();
solver.iterations = 7;
solver.tolerance = 0.1;
world.solver = solver;
world.quatNormalizeSkip = 0;
world.quatNormalizeFast = false;
world.defaultContactMaterial.contactEquationStiffness = 1e9;
world.defaultContactMaterial.contactEquationRelaxation = 4;
return world;
}
/**
* Generate the materials to be used for contacts
**/
function getPhysicsMaterial() {
var physicsMaterial = new CANNON.Material('slipperyMaterial');
var physicsContactMaterial = new CANNON.ContactMaterial(
physicsMaterial, physicsMaterial, 0.0, 0.3)
world.addContactMaterial(physicsContactMaterial);
return physicsMaterial;
}
/**
* Add objects to the world
**/
function addObjectPhysics() {
addFloorPhysics()
addSpherePhysics()
}
function addFloorPhysics() {
floors.map(function(floor) {
var q = floor.quaternion;
floorBody = new CANNON.Body({
mass: 0, // mass = 0 makes the body static
material: physicsMaterial,
shape: new CANNON.Plane(),
quaternion: new CANNON.Quaternion(-q._x, q._y, q._z, q._w)
});
world.addBody(floorBody);
})
}
function addSpherePhysics() {
sphereBody = new CANNON.Body({
mass: 1,
material: physicsMaterial,
shape: new CANNON.Sphere(30),
linearDamping: 0.5,
position: new CANNON.Vec3(1000, 500, -2000)
});
world.addBody(sphereBody);
}
/**
* Store all currently pressed keys & handle window resize
**/
function addListeners() {
window.addEventListener('keydown', function(e) {
pressed[e.key.toUpperCase()] = true;
})
window.addEventListener('keyup', function(e) {
pressed[e.key.toUpperCase()] = false;
})
window.addEventListener('resize', function(e) {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
if (typeof(controls) != 'undefined') controls.handleResize();
})
}
/**
* Update the sphere's position
**/
function moveSphere() {
var delta = clock.getDelta(); // seconds
var moveDistance = 500 * delta; // n pixels per second
var rotateAngle = Math.PI / 2 * delta; // 90 deg per second
// move forwards, backwards, left, or right
if (pressed['W'] || pressed['ARROWUP']) {
sphereBody.velocity.z += moveDistance;
}
if (pressed['S'] || pressed['ARROWDOWN']) {
sphereBody.velocity.z -= moveDistance;
}
if (pressed['A'] || pressed['ARROWLEFT']) {
sphereBody.velocity.x += moveDistance;
}
if (pressed['D'] || pressed['ARROWRIGHT']) {
sphereBody.velocity.x -= moveDistance;
}
}
/**
* Follow the sphere
**/
function moveCamera() {
camera.position.x = sphereBody.position.x + 0;
camera.position.y = sphereBody.position.y + 50;
camera.position.z = sphereBody.position.z + -200;
camera.lookAt(sphereGroup.position);
}
function updatePhysics() {
world.step(1/60);
sphereGroup.position.copy(sphereBody.position);
sphereGroup.quaternion.copy(sphereBody.quaternion);
}
// Render loop
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
moveSphere();
updatePhysics();
if (typeof(controls) === 'undefined') moveCamera();
if (typeof(controls) !== 'undefined') controls.update();
if (typeof(stats) !== 'undefined') stats.update();
};
// state
var pressed = {};
var clock = new THREE.Clock();
// globals
var scene = getScene();
var camera = getCamera();
var light = getLight(scene);
var renderer = getRenderer();
var world = getPhysics();
var physicsMaterial = getPhysicsMaterial();
//var stats = getStats();
//var controls = getControls(camera, renderer);
// global body references
var sphereBody, floorBody;
// add meshes
var loader = new THREE.TextureLoader();
var floors = getPlanes(scene, loader);
var background = getBackground(scene, loader);
var sphereData = getSphere(scene);
var sphere = sphereData[0];
var sphereGroup = sphereData[1];
addObjectPhysics();
addListeners();
render();
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100%; }
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js'></script>
Answers to comment questions
#jparimaa I think the most intuitive implementation would make W add forward momentum, S add backward momentum, and A and D rotate the camera around the ball. Is that possible?
#HariV The controls you link to are the ones I used in the demo without physics above. Is it possible to get that logic working with physics?
I think it's most intuitive for users if the W key always moves the ball "forward" relative to the camera
One option would be to calculate the direction between the ball and the camera and add velocity to that direction. In this case if you push the ball forward then you could rotate the camera without it affecting the velocity of the ball. Only after you press W/S after the rotation it would change the direction. I'm not sure if that is what you want but maybe this will give you some ideas.
I tried the following code (rotation is global variable initialized to 0)
function moveSphere() {
var delta = clock.getDelta(); // seconds
var moveDistance = 500 * delta; // n pixels per second
var dir = new THREE.Vector3(sphereBody.position.x, sphereBody.position.y, sphereBody.position.z);
dir.sub(camera.position).normalize(); // direction vector between the camera and the ball
if (pressed['W'] || pressed['ARROWUP']) {
sphereBody.velocity.x += moveDistance * dir.x;
sphereBody.velocity.z += moveDistance * dir.z;
}
if (pressed['S'] || pressed['ARROWDOWN']) {
sphereBody.velocity.x -= moveDistance * dir.x;
sphereBody.velocity.z -= moveDistance * dir.z;
}
}
function moveCamera() {
var delta = clock.getDelta();
var sensitivity = 150;
var rotateAngle = Math.PI / 2 * delta * sensitivity;
if (pressed['A'] || pressed['ARROWLEFT']) {
rotation -= rotateAngle;
}
if (pressed['D'] || pressed['ARROWRIGHT']) {
rotation += rotateAngle;
}
var rotZ = Math.cos(rotation)
var rotX = Math.sin(rotation)
var distance = 200;
camera.position.x = sphereBody.position.x - (distance * rotX);
camera.position.y = sphereBody.position.y + 50;
camera.position.z = sphereBody.position.z - (distance * rotZ);
camera.lookAt(sphereGroup.position);
}
I'm trying to rotate multiple objects around the same Vector3 point but in different directions - so they effectively 'swarm' around the point.
I'm using the trig approach rather simply wrapping each object in a Container and applying some random rotations as I'm projecting their 3D vector to 2D positions to attach label DIVs above the canvas, and the container approach messes with with project class.
Here's my current code which makes all objects rotate around the point along the same orbit path:
for(var i = 0; i<objectsArr.length; i++){
var obj = objectsArr[i];
var radius = obj.angle * (Math.PI / 180);
obj.position.x = obj.radius * Math.cos(radius);
obj.position.y = obj.radius * Math.sin(radius);
obj.angle += obj.orbitSpeed;
}
Does anyone know how I can make them orbit in random directions along X, Y, Z axis?
First, see this answer about rotating objects about a point.
From your code, it looks like you're storing each object's orbit speed, and their current angle of rotation (which represents the vector to the position). Rather than storing a 2D angle, store it as a Vector3 which represents the normal of (perpendicular to) the object's orbital plane. (This will let you really get a "swarm" going later, when you can define different orbital planes.) I also recommend storing the orbit speed in radians per step, so you don't have to perform the conversion every pass.
The rest of problem actually becomes very simple with the Vector3.applyAxisAngle method.
Some pseudo-code:
Subtract the rotation point position from the object's position.
Use the object's orbit speed, and angle to update the temp position.
Add the rotation point position back to the object's position.
To see it in your code:
var obj;
for(var i = 0; i< objectsArr.length; i++){
obj = objectsArr[i];
obj.position.sub(rotationPoint); // rotationPoint is a Vector3
obj.position.applyAxisAngle(obj.angle, obj.orbitSpeed);
obj.add(rotationPoint);
}
And here's a live demo of a few objects orbiting randomly about a "nucleus" at (10, 10, 10).
var renderer, scene, camera, controls, stats, nucleus;
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight,
FOV = 60,
NEAR = 1,
FAR = 1000;
var electrons = [],
numElectrons = 100; // more electrons = slower updating
function populateScene() {
var geo = new THREE.SphereBufferGeometry(10, 16, 16);
var mat = new THREE.MeshPhongMaterial({color:"blue"});
nucleus = new THREE.Mesh(geo, mat);
nucleus.position.set(10, 10, 10); // you can change these values
scene.add(nucleus);
var electron = null,
plane = new THREE.Plane(),
point = new THREE.Vector3();
geo = new THREE.SphereBufferGeometry(1, 16, 16);
mat = new THREE.MeshPhongMaterial({color:"red"});
for(var i = 0; i < numElectrons; ++i){
electron = new THREE.Mesh(geo, mat);
electrons.push(electron);
electron.angle = new THREE.Vector3(
Math.random(),
Math.random(),
Math.random()
).normalize();
electron.orbitSpeed = (Math.random() * 0.05) + 0.05;
if(Math.random() > 0.5) electron.orbitSpeed *= -1;
plane.normal.copy(electron.angle);
point.set(Math.random(), Math.random(), Math.random());
plane.projectPoint(point, electron.position);
electron.position.setLength(Math.floor(Math.random() * 20) + 15);
electron.position.applyAxisAngle(electron.angle, Math.random() / 10);
electron.position.add(nucleus.position);
scene.add(electron);
}
}
function updateElectrons(){
var obj = null;
for(var i = 0; i < numElectrons; ++i){
obj = electrons[i]
obj.position.sub(nucleus.position);
obj.position.applyAxisAngle(obj.angle, obj.orbitSpeed);
obj.position.add(nucleus.position);
}
}
function init() {
document.body.style.backgroundColor = "slateGray";
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
document.body.style.overflow = "hidden";
document.body.style.margin = "0";
document.body.style.padding = "0";
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 100;
scene.add(camera);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.dynamicDampingFactor = 0.5;
controls.rotateSpeed = 3;
var light = new THREE.PointLight(0xffffff, 1, Infinity);
camera.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);
resize();
window.onresize = resize;
populateScene();
animate();
}
function resize() {
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
if (renderer && camera && controls) {
renderer.setSize(WIDTH, HEIGHT);
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix();
controls.handleResize();
}
}
function render() {
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
updateElectrons();
render();
controls.update();
stats.update();
}
function threeReady() {
init();
}
(function() {
function addScript(url, callback) {
callback = callback || function() {};
var script = document.createElement("script");
script.addEventListener("load", callback);
script.setAttribute("src", url);
document.head.appendChild(script);
}
addScript("https://threejs.org/build/three.js", function() {
addScript("https://threejs.org/examples/js/controls/TrackballControls.js", function() {
addScript("https://threejs.org/examples/js/libs/stats.min.js", function() {
threeReady();
})
})
})
})();
three.js r86
Running into a bit of a problem with Three.js. I'm currently trying to move particles within a particle system when each frame is rendered. No errors are being reported, but nothing is moving either! The example I took from the code at http://aerotwist.com/tutorials/creating-particles-with-three-js/ uses the syntax particle.position.y, but the JS console returns Cannot set property 'y' of undefined when I change the below code to mirror that. Any help or pointers on where I'm going wrong is much appreciated.
Full source code:
var scene, camera, renderer, particleCount = 0, particleSystem, particles;
init();
animate();
function init()
{
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
scene.add(camera);
camera.position.z = 5;
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
particleCount = 1800,
particles = new THREE.Geometry();
var pMaterial = new THREE.ParticleBasicMaterial({color: 0xFFFFFF, size: 0.5});
for (var i = 0; i < particleCount; i++)
{
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vector3(pX, pY, pZ);
particles.vertices.push(particle);
}
particleSystem = new THREE.ParticleSystem(particles, pMaterial);
scene.add(particleSystem);
}
function animate()
{
requestAnimationFrame(animate);
renderer.render(scene, camera);
var pCount = particleCount;
while (pCount--)
{
var particle = particles.vertices[pCount];
particle.y = Math.random() * 500 - 250;
particleSystem.geometry.vertices.needsUpdate = true;
}
}
It seems like you have to add particleSystem.sortParticles = true; after creating your particleSystem.
I encountered exactly the same issue in the same tutorial but, using ThreeJS 86, I needed neither the setY() nor the particleSystem.sortParticles = true; but particleSystem.geometry.verticesNeedUpdate = true; (not particleSystem.geometry.vertices.needsUpdate = true;).
I am trying to input some known acr values from another program and reproduce them in three.js
Right now I am using the following code I found on this site. It draw the arc fine, although it may not be the best option.
function DRAWarc(){
// smooth my curve over this many points
var numPoints = 100;
spline = new THREE.SplineCurve3([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 200, 0),
new THREE.Vector3(150, 150, 0)
]);
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var splinePoints = spline.getPoints(numPoints);
for(var i = 0; i < splinePoints.length; i++){
geometry.vertices.push(splinePoints[i]);
}
var line = new THREE.Line(geometry, material);
scene.add(line);
}
The following are the known variables.
Center point (X,Y) (if the are was a complete circle, the center of the circle)
radius (if it were a circle)
start angle (I'm not positive, but I think this is the degree, if it were a circle, going counter-clockwise, with 0 being to the right of the circle)
end angle (see above)
more code!
///////////
// SCENE //
///////////
scene = new THREE.Scene();
////////////
// CAMERA //
////////////
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
viewsize = 900;
camera = new THREE.OrthographicCamera(
SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2,
SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2,
1, 1e6 );
camera.position.z = 2000;
scene.add(camera);
camera.lookAt(new THREE.Vector3(2100, 3600, 0));
//////////////
// RENDERER //
//////////////
// create and start the renderer
if ( Detector.webgl ){
renderer = new THREE.WebGLRenderer();
//alert('no problem.');
}else{
renderer = new THREE.CanvasRenderer();
alert('problem.');
}
renderer.setClearColor("white", 1);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.body;
container.appendChild( renderer.domElement );
////////////
// EVENTS //
////////////
// automatically resize renderer
THREEx.WindowResize(renderer, camera);
// toggle full-screen on given key press
THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
///////////
// STATS //
///////////
// displays current and past frames per second attained by scene
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
///////////
// LIGHT //
///////////
// create a light
var light = new THREE.PointLight(0xffffff);
light.position.set(0,250,0);
scene.add(light);
var ambientLight = new THREE.AmbientLight(0x111111);
// scene.add(ambientLight);
//////////////
// GEOMETRY //
//////////////
// most objects displayed are a "mesh":
// a collection of points ("geometry") and
// a set of surface parameters ("material")
doWork();
}
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
function update()
{
// delta = change in time since last call (in seconds)
var delta = clock.getDelta();
// functionality provided by THREEx.KeyboardState.js
if ( keyboard.pressed("1") )
document.getElementById('message').innerHTML = ' Have a nice day! - 1';
if ( keyboard.pressed("2") )
document.getElementById('message').innerHTML = ' Have a nice day! - 2 ';
//controls.update();
stats.update();
}
function render()
{
renderer.render( scene, camera );
}`
You can draw arc with the circle geometry
// compute angle between p1 and p2
var angle = Math.acos(p1.dot(p2)/(p1.length()*p2.length()));
// create arc
var geometry = new THREE.CircleGeometry(radius, nbSegments, 0, angle);
// remove center vertex
geometry.vertices.splice(0,1);
// TODO: move the arc to the good place in the scene
// add arc to the scene
scene.add(new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0xff00f0 }));
So after a little research I found the following post.
How do I calculate a point on a circle’s circumference?
which led me to this bit of math that can be adapted to any language:
x = cx + r * cos(a)
y = cy + r * sin(a)
Where r is the radius, cx,cy the origin, and a the angle from 0..2PI radians or 0..360 degrees.
and heres some fun reading material!
http://en.wikipedia.org/wiki/Circle#Equations
EDIT: just completed the rough draft for this project. enjoi!
i does not draw a spline, instead it draws a line with 102 points. the start of the arc, the end, and 100 evenly spaced points in between. it works well, and i will add a variable to the number of lines to reduce memory if needed.
function getARC(x, y, r, a){
a = a * (Math.PI/180);
var ax = +x + +r * Math.cos(+a),
ay = +y + +r * Math.sin(+a),
res = [];
res['x'] = ax,
res['y'] = ay;
return res;
}
function DRAWarc(cx, cy, ra, sa, ea){
var cx = '2473.5737';
var cy = '3145.1300';
var ra = '47.5538';
var sa = '2';
var ea = '91';
var material = new THREE.LineBasicMaterial({
color: 0xff00f0,
});
var geometry = new THREE.Geometry();
var s = getARC(cx, cy, ra, sa);
geometry.vertices.push(new THREE.Vector3(s['x'], s['y'], 0));
var step = (ea - sa)/100;
for(var i=1;i<=100;i++){
var t = getARC(cx, cy, ra, (+sa + (+step * +i)));
geometry.vertices.push(new THREE.Vector3(t['x'], t['y'], 0));
//alert((+sa + (+step * +i)));
}
var f = getARC(cx, cy, ra, ea);
geometry.vertices.push(new THREE.Vector3(f['x'], f['y'], 0));
var line = new THREE.Line(geometry, material);
scene.add(line);
}