I want to make my FBX model rotate continuously using three.js.
So I tried
make my object into variable
call my object in animate function to rotate. (girl1)
but I got an error:
Cannot read property 'rotation' of undefined.
My code is like this:
function init() {
...
// zombie girl
let loader_girl = new FBXLoader();
loader_girl.load("ZombiePunching.fbx", (object) => {
// animation mixer
mixer = new THREE.AnimationMixer(object);
const action = mixer.clipAction(object.animations[0]);
action.play();
// make materials opaque
object.traverse((child) => {
if (child.isMesh) {
child.material.transparent = false;
}
});
object.scale.set(0.05, 0.05, 0.05);
object.rotation.x = Math.PI;
scene.add(object);
girl1 = object;
});
...
let loader = new THREE.TextureLoader();
loader.load("smoke.png", function (texture) {
let cloudGeo = new THREE.PlaneBufferGeometry(500, 500);
let cloudMaterial = new THREE.MeshLambertMaterial({
map: texture,
transparent: true,
});
for (let p = 0; p < 25; p++) {
let cloud = new THREE.Mesh(cloudGeo, cloudMaterial);
cloud.position.set(
Math.random() * 800 - 400,
500,
Math.random() * 500 - 450
);
cloud.rotation.x = 1.16;
cloud.rotation.y = -0.12;
cloud.rotation.z = Math.random() * 360;
cloud.material.opacity = 0.6;
cloudParticles.push(cloud);
scene.add(cloud);
}
});
}
function animate() {
cloudParticles.forEach((p) => {
p.rotation.z -= 0.002;
});
rainGeo.vertices.forEach((p) => {
p.velocity -= 0.1 + Math.random() * 0.1;
p.y += p.velocity;
if (p.y < -200) {
p.y = 200;
p.velocity = 0;
}
});
rainGeo.verticesNeedUpdate = true;
rain.rotation.y += 0.002;
girl1.rotation.y += 0.001;
if (Math.random() > 0.93 || flash.power > 100) {
if (flash.power < 100)
flash.position.set(Math.random() * 400, 300 + Math.random() * 200, 100);
flash.power = 50 + Math.random() * 500;
}
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
init();
animate();
Instead of doing this:
girl1.rotation.y += 0.001;
try it with:
if ( girl1 ) girl1.rotation.y += 0.001;
Since you start the animation loop before the FBX is actually loaded, girl1 will be undefined for a certain amount of time.
Related
I'm trying to make a database of words where the most important words are closer to the top of the sphere and the less important are further away. So I created a sphere with enough vertices for each word, created a list of those vertices in order of distance from the top of the sphere, and placed the text sprites at the positions of the vertices in order of that sorted list.
Video version: https://i.gyazo.com/aabaf0b4a26f4413dc6a0ebafab2b4bd.mp4
Sounded like a good plan in my head, but clearly the geometry of a sphere causes the words to be further spread out the further away from the top they are. I need a result that looks like a somewhat even distribution across the surface. It doesn't have to be perfect, just visually closer than this.
How can I achieve the desired effect?
Here are the relevant methods:
positionDb(db) {
console.log("mostRelated", db.mostRelated);
console.log("depthList", this.depthList);
let mostRelated = db.mostRelated;
let depthList = this.depthList;
for (let i = 0; i < mostRelated.length; i++) {
this.addTextNode(mostRelated[i].data, this.depthList[i].vertice, this.depthList[i].depth);
}
}
addTextNode(text, vert, distance) {
let fontSize = 0.5 * (600 / distance);
let sprite = new THREE.TextSprite({
fillStyle: '#000000',
fontFamily: '"Arial", san-serif',
fontSize: fontSize,
fontWeight: 'bold',
text: text
});
this.scene.add(sprite);
sprite.position.set(vert.x, vert.y, vert.z);
setTimeout(() => {
sprite.fontFamily = '"Roboto", san-serif';
}, 1000)
}
this.scene = scene;
this.geometry = new THREE.SphereGeometry(420, 50, 550);
var material = new THREE.MeshBasicMaterial({
color: 0x0011ff
});
var sphere = new THREE.Mesh(this.geometry, wireframe);
var wireframe = new THREE.WireframeGeometry(this.geometry);
let frontVert = {
x: 0,
y: 100,
z: 0
}
let depthList = [];
this.geometry.vertices.forEach(vertice => {
let depth = getDistance(frontVert, vertice);
if (depthList.length === 0) {
depthList.push({
depth,
vertice
});
} else {
let flag = false;
for (let i = 0; i < depthList.length; i++) {
let item = depthList[i];
if (depth < item.depth) {
flag = true;
depthList.splice(i, 0, {
depth,
vertice
});
break;
}
}
if (!flag) depthList.push({
depth,
vertice
});
}
});
Maybe a fibonacci sphere
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
Example:
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
function main() {
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
function addTextNode(text, vert) {
const div = document.createElement('div');
div.className = 'label';
div.textContent = text;
div.style.marginTop = '-1em';
const label = new THREE.CSS2DObject(div);
label.position.copy(vert);
scene.add(label);
}
const renderer = new THREE.CSS2DRenderer();
const container = document.querySelector('#c');
container.appendChild(renderer.domElement);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
const numPoints = 50;
for (let i = 0; i < numPoints; ++i) {
addTextNode(`p${i}`, fibonacciSphere(numPoints, i));
}
function render(time) {
time *= 0.001;
// three's poor choice of how to hanlde size strikes again :(
renderer.setSize(container.clientWidth, container.clientHeight);
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
body {
margin: 0;
overflow: hidden;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
.label {
color: red;
}
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.min.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/renderers/CSS2DRenderer.js"></script>
<div id="c"></div>
I'm completely new to three.js and 3D. I'm trying to make a really simple first person shooter. I found heaps of examples but they all look really complicated. I want to understand the code before I use it. What I am having trouble with is the camera rotation. Everything else is fine. My approach doesn't quite work. It seems to be rotating on the z axis even though I'm setting that to 0. Here's all my code (125 lines)
var width = window.innerWidth, height = window.innerHeight,
scene = new THREE.Scene(),
camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000),
renderer = new THREE.WebGLRenderer(),
mouse = {
x: 0,
y: 0,
movedThisFrame: false
};
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
var floorgeometry = new THREE.BoxGeometry(100,0.1,100);
var floormaterial = new THREE.MeshBasicMaterial({
color: 0xff0000
});
var floor = new THREE.Mesh(floorgeometry, floormaterial);
floor.position.y = -1;
scene.add(floor);
var keys = {
w: false,
a: false,
s: false,
d: false
};
camera.position.z = 5;
function radDeg(radians) {
return radians * 180 / Math.PI;
}
function degRad(degrees) {
return degrees * Math.PI / 180;
}
function rotateCam() {
if (!mouse.movedThisFrame) {
mouse.x = 0;
mouse.y = 0;
}
/*
What am I doing wrong here?
*/
camera.rotation.x -= mouse.y * 0.001;
camera.rotation.y -= mouse.x * 0.001;
camera.rotation.z = 0;
mouse.movedThisFrame = false;
}
function moveCam() {
var rotation = camera.rotation.y % (Math.PI * 2), motion = [0,0];
if (keys.w) {
motion[0] += 0.1 * Math.cos(rotation);
motion[1] += 0.1 * Math.sin(rotation);
}
if (keys.a) {
motion[0] += 0.1 * Math.cos(rotation + degRad(90));
motion[1] += 0.1 * Math.sin(rotation + degRad(90));
}
if (keys.s) {
motion[0] += 0.1 * Math.cos(rotation - degRad(180));
motion[1] += 0.1 * Math.sin(rotation - degRad(180));
}
if (keys.d) {
motion[0] += 0.1 * Math.cos(rotation - degRad(90));
motion[1] += 0.1 * Math.sin(rotation - degRad(90));
}
camera.position.z -= motion[0];
camera.position.x -= motion[1];
}
window.onload = function() {
renderer.domElement.onclick = function() {
console.log('requested pointer lock');
renderer.domElement.requestPointerLock();
};
renderer.domElement.onmousemove = function(e) {
if (!mouse.movedThisFrame) {
mouse.x = e.movementX;
mouse.y = e.movementY;
mouse.movedThisFrame = true;
}
};
document.onkeydown = function(e) {
var char = String.fromCharCode(e.keyCode);
if (char == 'W')
keys.w = true;
else if (char == 'A')
keys.a = true;
else if (char == 'S')
keys.s = true;
else if (char == 'D')
keys.d = true;
};
document.onkeyup = function(e) {
var char = String.fromCharCode(e.keyCode);
if (char == 'W')
keys.w = false;
else if (char == 'A')
keys.a = false;
else if (char == 'S')
keys.s = false;
else if (char == 'D')
keys.d = false;
};
function animate() {
requestAnimationFrame(animate);
rotateCam();
moveCam();
renderer.render(scene, camera);
}
animate();
};
The problem is in the rotateCam function. It doesn't quite work and I don't really know why.
I also tried using the code on this question but it didn't work.
First person controls are more complicated than you may think. Even if you figure out your angle math, when the pointer is not locked, the mouse hits the window edge and turning stops.
I suggest you start with the pointer lock example (http://threejs.org/examples/#misc_controls_pointerlock) which is an example of first person controls for 3js.
I am attempting to turn 3D objects into clickable elements by using an array called objects[]; and a switch statement which accesses the userData of the object. Right now, the script runs with no errors yet the objects still aren't clickable. What am I missing?
var container, stats;
var camera, scene, raycaster, renderer;
var mouse = new THREE.Vector2(),
INTERSECTED;
var radius = 100,
theta = 0;
init();
animate();
function createMesh(name, geometry, material) {
var object = new THREE.Mesh(geometry, material);
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() * 2 + 1;
object.scale.y = Math.random() * 2 + 1;
object.scale.z = Math.random() * 2 + 1;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.userData = {
URL: "http://www.google.com"
};
var objects = [];
for (i = 0; i > objects.length; i++) {
objects += i;
objects.push(object);
}
scene.add(object);
switch (i) {
case 1:
objects[i].userData = {
URL: "http://www.google.com"
};
break;
case 2:
objects[i].userData = {
URL: "https://www.yahoo.com"
};
break;
}
object.name = name;
}
var objects = [];
// objects.length == 0
// i is not greater than so nothing happens
for (i = 0; i > objects.length; i++) {
objects += i;
objects.push(object);
}
scene.add(object);
// i is still equal to 0 so nothing happens once again
switch (i) {
case 1: ...
case 2: ...
I am creating a THREEjs animation which I eventually want to sync with audio. (Can't accomplish this currently) I would like to add and remove shaders at specific points. How can I accomplish this most efficiently?
The way I have it set up now, is that I have a mirror shader inside of a function called turnOnMirror and in my render function, I have a conditional statement,
if (audioSrc.context.currentTime > 32.0) { turnOnMirror(); }
The shader looks like this:
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
(I am doing this for 2 reasons!
A: The renderer is the only place I can grab the actual time to make this call. And B: because for whatever reason, my frequencyData array comes back as 0s.
However, when the scene reaches this point, everything slows down extremely. How can I keep the same frame rate and accomplish what I am attempting to at the same time?
A piece of information for you is that the scene works fine at the same constant speed if I just apply the shader without making the call in the render function.
You can view the site here!
And the source code for the main.js is below!
/* ==================== [ Global Variables ] ==================== */
var scene, camera, renderer, aspectRatio;
var stats;
var composer, effect, clock;
var backMesh;
/* ==================== [ Audio Context ] ==================== */
var ctx = new AudioContext();
var audio = document.getElementById('player');
audio.play();
audio.volume = 1;
// audio.crossOrigin = "anonymous";
var audioSrc = ctx.createMediaElementSource(audio);
var analyser = ctx.createAnalyser();
audioSrc.connect(analyser);
audioSrc.connect(ctx.destination);
// frequencyBinCount tells you how many values you'll receive from the analyser
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(frequencyData);
console.log(audioSrc);
console.log(audioSrc.context.currentTime);
console.log(frequencyData);
console.log(analyser.fftSize); // 2048 by default
console.log(analyser.frequencyBinCount); // will give us 1024 data points
analyser.fftSize = 64;
console.log(analyser.frequencyBinCount); // fftSize/2 = 32 data points
/* ==================== [ Set Scene & Camera ] ==================== */
scene = new THREE.Scene();
// scene.fog = new THREE.Fog(0x000000, 0, 1200);
aspectRatio = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 100);
// camera.target = new THREE.Vector3( 10, 10, 10 );
// Set the DOM
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("#000000");
document.body.appendChild(renderer.domElement);
/* ==================== [ Camera Position ] ==================== */
camera.position.z = 15;
camera.position.y = 0;
/* ==================== [ Point Lights ] ==================== */
var pointLightBlue = new THREE.PointLight("#00ccff", 5, 100, 2);
pointLightBlue.position.set(-10, -40, -10);
scene.add(pointLightBlue);
// var pointLightWhite = new THREE.PointLight( "#ffffff", 1, 0, 1 );
// // pointLightWhite.position.set( -10, 160, -10 );
// pointLightWhite.position.set( 0, 0, 1 );
// scene.add(pointLightWhite);
// camera.add(pointLightWhite);
// var pointLightPink = new THREE.PointLight( "#EE567C", 5, 100, 10 );
// pointLightPink.position.set( 1, 0, -5 );
// scene.add(pointLightPink);
var pointLight = new THREE.PointLight("#A805FA", 2, 100, 40);
pointLight.position.set(40, 0, 40);
scene.add(pointLight);
var light2 = new THREE.PointLight( 0xFFFFFF, 1, 100 );
scene.add( light2 );
light2.position.z = 1000;
var pointLight2 = new THREE.PointLight("#07FAA0", 2, 100, 30);
pointLight2.position.set(-40, 0, -40);
scene.add(pointLight2);
/* ==================== [ Particles ] ==================== */
var getCamera = function() {
return camera;
}
// var texture = new Image();
// texture.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/82015/snowflake.png';
// texture.src = './images/particle.png';
//var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture(texture) } );
var particleCount = 0, particleSystem, particles;
THREE.ImageUtils.crossOrigin = '';
var texture = THREE.ImageUtils.loadTexture('./images/particle.png');
//console.log(texture);
particleCount = 20000,
particles = new THREE.Geometry();
var pMaterial = new THREE.PointCloudMaterial({
color: 0xFFFFFF,
map: texture,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
size: 1.2
});
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);
particleSystem.sortParticles = false;
particleSystem.frustumCulled = false;
scene.add(particleSystem);
/* ==================== [ Light Beams ] ==================== */
var BEAM_ROT_SPEED = 0.003;
var BEAM_COUNT = 360;
var beamGeometry = new THREE.PlaneBufferGeometry(1, 500, 10, 1);
beamGroup = new THREE.Object3D();
beamMaterial = new THREE.MeshBasicMaterial({
opacity: 0.02,
transparent: true,
});
for (var i = 0; i <= BEAM_COUNT; ++i) {
var beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.doubleSided = true;
beam.rotation.x = Math.random() * Math.PI;
beam.rotation.y = Math.random() * Math.PI;
beam.rotation.z = Math.random() * Math.PI;
beamGroup.add(beam);
}
scene.add(beamGroup);
beamGroup.translateZ( -5 );
/* ==================== [ Cubes ] ==================== */
var doStrobe = false;
var doShake = false;
var strobeOn = false;
var beatTime = 30;
THREE.ImageUtils.crossOrigin = '';
var imgTextureStripes2 = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
imgTextureStripes2.wrapS = imgTextureStripes2.wrapT = THREE.RepeatWrapping;
imgTextureStripes2.repeat.set( 100, 100 );
backMaterial2 = new THREE.MeshBasicMaterial( {
map:imgTextureStripes2
} );
backMesh2 = new THREE.Mesh( new THREE.SphereGeometry( 1900, 30, 20 ), backMaterial2 );
backMesh2.scale.x = -1;
scene.add( backMesh2 );
backMesh2.visible = false;
function Box() {
this.posn = new THREE.Vector3();
this.rotation = new THREE.Vector3();
this.speed = getRand(3, 20);
this.init();
}
Box.ORIGIN = new THREE.Vector3();
Box.MAX_DISTANCE = 1000;
Box.INIT_POSN_RANGE = 500;
Box.FRONT_PLANE_Z = 1000;
Box.BACK_PLANE_Z = -1000;
Box.prototype.init = function() {
this.posn.copy(Box.ORIGIN);
this.posn.x = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.y = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.z = Box.BACK_PLANE_Z;
this.rotation.x = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.y = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.z = (Math.random() * 360 ) * Math.PI / 180;
};
Box.prototype.update = function() {
this.posn.z += this.speed * sketchParams.cubeSpeed ;
this.rotation.x += 0.03;
this.rotation.y += 0.01;
if(this.posn.z > Box.FRONT_PLANE_Z) {
this.init();
}
};
// returns random number within a range
function getRand(minVal, maxVal) {
return minVal + (Math.random() * (maxVal - minVal));
}
var cubesize = 100;
var BOX_COUNT;
var geometry = new THREE.CubeGeometry(cubesize, cubesize, cubesize);
cubeHolder = new THREE.Object3D();
THREE.ImageUtils.crossOrigin = '';
imgTextureStripes = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
cubeMaterial = new THREE.MeshPhongMaterial( {
ambient: 0x111111,
color: 0x666666,
specular: 0x999999,
shininess: 30,
shading: THREE.FlatShading,
map:imgTextureStripes
});
for(i = 0; i < BOX_COUNT; i++) {
var box = new Box();
console.log(box);
boxes.push(box);
var cube = new THREE.Mesh(geometry,cubeMaterial );
cube.position = box.posn;
cube.rotation = box.rotation;
cube.ox = cube.scale.x = Math.random() * 1 + 1;
cube.oy = cube.scale.y = Math.random() * 1 + 1;
cube.oz = cube.scale.z = Math.random() * 1 + 1;
cubeHolder.add(cube);
}
scene.add(cubeHolder);
/* ==================== [ Mini Geometries ] ==================== */
/* ==================== [ Post Processing ] ==================== */
composer = new THREE.EffectComposer(renderer);
composer.addPass(new THREE.RenderPass(scene, camera));
effect = new THREE.ShaderPass(THREE.FilmShader);
effect.uniforms['time'].value = 2.0;
effect.uniforms['nIntensity'].value = 0.4;
effect.uniforms['sIntensity'].value = 0.9;
effect.uniforms['sCount'].value = 1800;
effect.uniforms['grayscale'].value = 0.8;
composer.addPass(effect);
// var dot = new THREE.ShaderPass( THREE.DotScreenShader );
// dot.uniforms[ 'scale' ].value = 400;
// dot.uniforms[ 'tDiffuse' ].value = 40;
// dot.uniforms[ 'tSize' ].value = new THREE.Vector2( 256, 256 );
// composer.addPass(dot);
// var kaleidoPass = new THREE.ShaderPass(THREE.KaleidoShader);
// kaleidoPass.uniforms['sides'].value = 3;
// kaleidoPass.uniforms['angle'].value = 45 * Math.PI / 180;
// composer.addPass(kaleidoPass);
// var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
// // mirror.uniforms[ "tDiffuse" ].value = 1.0;
// // mirror.uniforms[ "side" ].value = 3;
// composer.addPass(mirror);
var glitch = new THREE.GlitchPass(64);
glitch.uniforms[ "tDiffuse" ].value = 1.0;
glitch.uniforms[ 'seed' ].value = Math.random() * 5;
glitch.uniforms[ 'byp' ].value = 0;
// glitch.goWild = true;
composer.addPass(glitch);
var superPass = new THREE.ShaderPass(THREE.SuperShader);
superPass.uniforms.vigDarkness.value = 1;
superPass.uniforms.vigOffset.value = 1.3;
superPass.uniforms.glowSize.value = 2;
superPass.uniforms.glowAmount.value = 1;
composer.addPass( superPass );
var tv = new THREE.ShaderPass( THREE.BadTVShader );
tv.uniforms[ "distortion" ].value = 1;
tv.uniforms[ "distortion2" ].value = .01;
// tv.uniforms[ "time" ].value = 1.5;
tv.uniforms[ "speed" ].value = 8.8;
tv.uniforms[ "rollSpeed" ].value = 0.8;
composer.addPass(tv);
var staticPass = new THREE.ShaderPass( THREE.StaticShader );
staticPass.uniforms[ "amount" ].value = 0.15;
staticPass.uniforms[ "size" ].value = 1.0;
staticPass.uniforms[ "time" ].value = 4.5;
composer.addPass(staticPass);
var effect1 = new THREE.ShaderPass(THREE.RGBShiftShader);
effect1.uniforms['amount'].value = 0.003;
effect1.renderToScreen = true;
composer.addPass(effect1);
function turnOnMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
}
function turnOffMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = false;
composer.addPass(mirror);
}
// add a timer
clock = new THREE.Clock;
/* ==================== [ Stats ] ==================== */
// stats = new Stats();
// stats.domElement.style.position = 'absolute';
// stats.domElement.style.left = '0px';
// stats.domElement.style.top = '0px';
// document.body.appendChild(stats.domElement);
// document.body.appendChild( renderer.domElement );
/* ==================== [ Shapes ] ==================== */
var quantity = 40;
var shapes = [];
for (var i = 0; i < quantity; i++) {
if (Math.random() < 0.5) {
var geometry = new THREE.RingGeometry(4, 40, 3);
// geometry.position = 0;
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// camera.position.z = 60;
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
}
else {
//var geometry = new THREE.RingGeometry( 4, 40, 3);
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// var geometry = new THREE.RingGeometry( 1, 5, 6 );
// var material = new THREE.MeshBasicMaterial( { color: 0xffff00,
// side: THREE.DoubleSide } );
// var mesh = new THREE.Mesh( geometry, material );
// scene.add( mesh );
}
if (i % 7 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#ffffff"
});
} else if (i % 2 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#666666"
});
} else {
var material = new THREE.MeshPhongMaterial({
color: "#333333"
});
}
var mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -i * 3;
// mesh.rotation.z = i;
shapes.push(mesh);
scene.add(mesh);
}
// function refRate() {
// curTime = Date.now();
// delta = curTime - oldTime;
//
// if (delta > interval) {
// oldTime = curTime - (delta % interval);
// updateSize();
// }
//
// }
// Variables
var u_time = 0;
/* ==================== [ Render Function ] ==================== */
var render = function () {
requestAnimationFrame(render);
// var timer = Date.now() * 0.0010;
// camera.lookAt(scene.position);
u_time++;
for (var i = 0; i < quantity; i++) {
// Set rotation change of shapes
shapes[i].position.z += 0.2;
shapes[i].rotation.z += 0;
shapes[i].scale.x = 1 + Math.sin(i + u_time * 0.1) * 0.05;
shapes[i].scale.y = 1 + Math.sin(i + u_time * 0.1) * 0.05;
// shapes[i].scale.y = 120 + Math.tan(i + u_time * 5.0) * 0.5;
// shapes[i].scale.x = 120 + Math.tan(i + u_time * 5.0) * 0.5;
var change = 1.5 + Math.sin(u_time * 0.5) * 0.5;
// Set wireframe & width
if (Math.random() < change) {
shapes[i].material.wireframe = false;
shapes[i].material.wireframeLinewidth = Math.random() * 2;
// if (shapes[i] / 2 === 0) {
// turnOnMirror();
// }
}
else {
shapes[i].material.wireframe = false;
}
if (shapes[i].position.z > 10) {
shapes[i].position.z = -70;
shapes[i].rotation.z = i;
}
}
// Set Point light Intensity & Position
pointLight.intensity = Math.abs(Math.sin(u_time * 0.2) * 2);
pointLight2.intensity = Math.abs(Math.cos(u_time * 0.2) * 2);
pointLight.position.z = Math.abs(Math.sin(u_time * 0.02) * 30);
pointLight2.position.z = Math.abs(Math.cos(u_time * 0.02) * 30);
renderer.render(scene, camera);
composer.render();
var pCount = particleCount;
while (pCount--) {
var camz = getCamera().position.z;
var particle = particles.vertices[pCount];
particle.y = Math.random() * 500 - 250;
//particleSystem.vertices[i].z = camz + Math.random()*600 + 200 ;
particleSystem.geometry.vertices.needsUpdate = true;
}
particleSystem.rotation.y += -0.001;
particleSystem.rotation.z += 0.005;
var normLevel = 0.2;
beamGroup.rotation.x += BEAM_ROT_SPEED;
beamGroup.rotation.y += BEAM_ROT_SPEED;
beamMaterial.opacity = Math.min(normLevel * 0.4, 0.6);
camera.rotation.z += 0.003;
if (doShake) {
var maxshake = 60;
var shake = normLevel * maxshake ;
camera.position.x = Math.random()*shake - shake/2;
camera.position.y = Math.random()*shake - shake/2;
}
camera.rotation.z += 0.003;
// camera.rotation.y += 0.005;
// camera.rotation.x -= 0.003;
//camera.rotation.z += 0.03;
if (doStrobe){
strobeOn = !strobeOn;
if (strobeOn){
light2.intensity = 2;
}
else {
light2.intensity = 0.5;
}
}
else {
light2.intensity = 0.2;
}
// flash background on level threshold
if (normLevel > 0.5 ){
renderer.setClearColor ( 0xFFFFFF );
backMesh2.visible = true;
}
else{
renderer.setClearColor ( 0x000000 );
backMesh2.visible = false;
}
// show stripes for 6 frames on beat
backMesh2.visible = beatTime < 6;
for(var i = 0; i < BOX_COUNT; i++) {
boxes[i].update();
}
if (audioSrc.context.currentTime > 32) {
turnOnMirror();
}
// console.log(audioSrc.context.currentTime);
}
render();
I am trying to do like this http://mbostock.github.io/protovis/ex/nbody.html and same project. But my system doesn't work. Can you help me This is my http://mendow.github.io/projects/n-body/index.html
I gues i am doing wrong in place calculating attration each part to each
Problem is particles has one mass center and spin around it instead has mass center which change it position
<!DOCTYPE html>
<html>
<head>
<title>n-body</title>
<script src="http://mendow.github.io/projects/n-body/libs/three.js"></script>
<script src="http://mendow.github.io/projects/n-body/libs/OrbitControls.js"></script>
<script src="http://mendow.github.io/projects/n-body/libs/OBJLoader.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<script>
//define global variable
{
var renderer;
var scene;
var camera;
var orbit;
var ps;
var G = 9.81;
var dt = 0.0001;
var count = 1000;
var cam = 30;
}
function init() {
{
// create a scene, that will hold all our elements such as objects, cameras and lights.
scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// create a render, sets the background color and the size
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x000000, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
// position and point the camera to the center of the scene
camera.position.x = cam;
camera.position.y = cam;
camera.position.z = cam;
camera.lookAt(scene.position);
orbit = new THREE.OrbitControls(camera);
}
setupParticleSystem(count);
// add the output of the renderer to the html element
document.body.appendChild(renderer.domElement);
// call the render function
render();
}
function setupParticleSystem(y) {
var geometry = new THREE.Geometry();
for (var j = 0; j < y; j++) {
var v = new THREE.Vector3();
var ran = 30;
v.x = intRand(ran, -ran);
v.y = intRand(ran, -ran);
v.z = intRand(ran, -ran);
v.vel = new THREE.Vector3(intRand(1, -1), intRand(1, -1), intRand(1, -1));
v.acc =new THREE.Vector3(intRand(1, -1), intRand(1, -1), intRand(1, -1));
v.mass = intRand(5, 0);
geometry.vertices.push(v);
}
console.log(geometry.vertices);
// use a material for some styling
var psMat = new THREE.PointCloudMaterial();
psMat.color = new THREE.Color(0x55ff55);
psMat.transparent = true;
psMat.size = 1;
psMat.blending = THREE.AdditiveBlending;
// Create a new particle system based on the provided geometry
ps = new THREE.PointCloud(geometry, psMat);
ps.sizeAttenuation = true;
ps.sortParticles = true;
ps.position.y = 100 / cam;
ps.position.x = 100 / cam;
ps.position.z = 100 / cam;
// add the particle system to the scene
scene.add(ps);
}
var step = 0;
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
var r,
mult;
var geometry = ps.geometry;
var temp = ps.geometry;
for (var i = 0; i < geometry.vertices.length; i++) {
for (var j = 0; j < geometry.vertices.length; j++) {
if (i != j) {
var particle = geometry.vertices[i];
var cntr = geometry.vertices[j];
r = particle.length(cntr);
mult = (-1) * G * (cntr.mass * particle.mass) / Math.pow(r, 3);
particle.acc.x = mult * particle.x;
particle.vel.x += particle.acc.x * dt;
particle.x += particle.vel.x * dt;
particle.acc.y = mult * particle.y;
particle.vel.y += particle.acc.y * dt;
particle.y += particle.vel.y * dt;
particle.acc.z = mult * particle.z;
particle.vel.z += particle.acc.z * dt;
particle.z += particle.vel.z * dt;
}
}
}
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
orbit.update();
}
// calls the init function when the window is done loading.
window.onload = init;
function mrand() {
return Math.random();
}
function intRand(min, max) {
return Math.random() * (max - min) + min;
}
</script>
<body>
</body>
</html>
When you examine your browser javascript console (F12) you will see this error :
Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at http://mendow.github.io/projects/n-body/assets/textures/ps_smoke.png may not be loaded.
One solution (see alternative solution below) is to simply put your asset files on same host as your HTML. That is local to your host computer. Here are the steps (linux cmds, amend for windows) :
cd into same dir as your html
mkdir -p assets/textures # create dir to park your ps_smoke.png
cd assets/textures # get into this new dir
# copy that remote file to your local dir
wget http://mendow.github.io/projects/n-body/assets/textures/ps_smoke.png
and then finally update your html
comment out :
psMat.map = THREE.ImageUtils.loadTexture("http://mendow.github.io/projects/n-body/assets/textures/ps_smoke.png");
good new location :
psMat.map = THREE.ImageUtils.loadTexture("assets/textures/ps_smoke.png");
Once I did this your code executes just fine.
Alternative to above solution is to just override this security check by adding following code just prior to the loadTexture call you are making :
THREE.ImageUtils.crossOrigin = '';
Matvey, you need to calculate the changes to all particle locations and velocities with the old values before adding them to get new values. Otherwise you're calculating some of the changes based on altered positions and velocities which is inaccurate.
I've edited your render loop:
<!DOCTYPE html>
<html>
<head>
<title>n-body</title>
<script src="http://mendow.github.io/projects/n-body/libs/three.js"></script>
<script src="http://mendow.github.io/projects/n-body/libs/OrbitControls.js"></script>
<script src="http://mendow.github.io/projects/n-body/libs/OBJLoader.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<script>
//define global variable
{
var renderer;
var scene;
var camera;
var orbit;
var ps;
var G = 9.81;
var dt = 0.0001;
var count = 1000;
var cam = 30;
}
function init() {
{
// create a scene, that will hold all our elements such as objects, cameras and lights.
scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// create a render, sets the background color and the size
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x000000, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
// position and point the camera to the center of the scene
camera.position.x = cam;
camera.position.y = cam;
camera.position.z = cam;
camera.lookAt(scene.position);
orbit = new THREE.OrbitControls(camera);
}
setupParticleSystem(count);
// add the output of the renderer to the html element
document.body.appendChild(renderer.domElement);
// call the render function
render();
}
function setupParticleSystem(y) {
var geometry = new THREE.Geometry();
for (var j = 0; j < y; j++) {
var v = new THREE.Vector3();
var ran = 30;
v.x = intRand(ran, -ran);
v.y = intRand(ran, -ran);
v.z = intRand(ran, -ran);
v.vel = new THREE.Vector3(intRand(1, -1), intRand(1, -1), intRand(1, -1));
v.acc =new THREE.Vector3(intRand(1, -1), intRand(1, -1), intRand(1, -1));
v.mass = intRand(5, 0);
geometry.vertices.push(v);
}
console.log(geometry.vertices);
// use a material for some styling
var psMat = new THREE.PointCloudMaterial();
psMat.color = new THREE.Color(0x55ff55);
psMat.transparent = true;
psMat.size = 1;
psMat.blending = THREE.AdditiveBlending;
// Create a new particle system based on the provided geometry
ps = new THREE.PointCloud(geometry, psMat);
ps.sizeAttenuation = true;
ps.sortParticles = true;
ps.position.y = 100 / cam;
ps.position.x = 100 / cam;
ps.position.z = 100 / cam;
// add the particle system to the scene
scene.add(ps);
}
var step = 0;
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
var r, mult;
var geometry = ps.geometry;
var temp = ps.geometry;
var dx = [];
var dv = [];
for (var i = 0; i < geometry.vertices.length; i++) {
var v = geometry.vertices[i].vel;
dx.push( new THREE.Vector3( v.x * dt, v.y * dt, v.z * dt ) );
var dvx = 0;
var dvy = 0;
var dvz = 0;
for (var j = 0; j < geometry.vertices.length; j++) {
if (i != j) {
mult = (-1) * G * geometry.vertices[i].mass * geometry.vertices[j].mass;
var vi = geometry.vertices[i];
var vj = geometry.vertices[j];
// http://www.scholarpedia.org/article/N-body_simulations_%28gravitational%29
epsilon = .1;
var r = Math.sqrt( ( vi.x - vj.x ) * ( vi.x - vj.x )
+ ( vi.y - vj.y ) * ( vi.y - vj.y )
+ ( vi.z - vj.z ) * ( vi.z - vj.z ) + epsilon )
dvx += mult * ( vi.x - vj.x ) / Math.pow( r, 3 );
dvy += mult * ( vi.y - vj.y ) / Math.pow( r, 3 );
dvz += mult * ( vi.z - vj.z ) / Math.pow( r, 3 );
}
}
dv.push( new THREE.Vector3( dvx * dt, dvy * dt, dvz * dt ) );
}
for ( var i=0 ; i < geometry.vertices.length ; i++ ) {
geometry.vertices[i].add( dx[i] );
geometry.vertices[i].vel.add( dv[i] );
}
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
orbit.update();
}
// calls the init function when the window is done loading.
window.onload = init;
function mrand() {
return Math.random();
}
function intRand(min, max) {
return Math.random() * (max - min) + min;
}
</script>
<body>
</body>
</html>
The modification to the denominator of the forces helps to keep energy relatively constant during close encounters of particles as per http://www.scholarpedia.org/article/N-body_simulations_(gravitational)