Using raycaster to highlight a row of meshes three.js - javascript

I am trying to use raycaster to identify a row of 3d cubes to be highlighted/colored on mousehover. I followed this post Change color of mesh using mouseover in three js. The issue I am facing is that it is only highlighting one cube i.e the cube the mouse is on and not the whole row. Please find my pseudocode below:
var cubesList = new THREE.Group();
function createScene () {
var cubeSize = 2;
for ( var i = 0; i < noOfEntries; i++ ) {
var entry = entries[ i ];
var entryObjects = entry.objects;
var entryCubesGroup = new THREE.Group();
var noOfObjects = entry.objects.length;
for ( var j = 0; j < noOfObjects; j++ ) {
var object = entryObjects[ j ];
var cube = createCube( cubeSize ); //THREE.Object3d group of 9 cubes
entryCubesGroup.add( cube );
if ( j === Math.round( noOfObjects / 4 ) - 1 && i === Math.round( noOfEntries / 4 ) - 1 ) {
cameraTarget = cube;
}
}
cubesList.add( entryCubesGroup );
}
scene.add( cubesList );
camera.position.x = 15;
camera.position.y = 15;
camera.position.z = 15;
camera.lookAt( new THREE.Vector3( cameraTarget.position.x, cameraTarget.position.y, cameraTarget.position.z ) );
var light = new THREE.PointLight( 0xffffff, 1, 0 );
light.position.set( 15, 15, 5 );
light.castShadow = true;
scene.add( light );
}
function animate () {
renderer.render( scene, camera );
update();
}
function onDocumentMouseMove ( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
mouse.y = -( event.clientY / renderer.domElement.height ) * 2 + 1;
animate();
}
function update() {
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
vector.unproject(camera);
var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersects = ray.intersectObjects(eventCubesList.children, true);
if (intersects.length > 0) {
if (intersects[0].object != INTERSECTED) {
if (highlightedRow)
unhighlightRow(highlightedRow);
INTERSECTED = intersects[0].object;
var timestamp = INTERSECTED.userData;
var selectedRow = getSelectedRow(timestamp);
highlightedRow = selectedRow;
highlightRow(selectedRow);
}
else {
if (INTERSECTED) {
if (highlightedRow) {
var timestamp = INTERSECTED.userData;
var row = getSelectedRow(timestamp);
unhighlightRow(row);
}
highlightedRow = null;
}
INTERSECTED = null;
}
}
function unhighlightRow(cubes) {
for (var i= 0; i < cubes.length; i++) {
var cube = cubes[i];
for (var j = 0; j < cube.children.length; j++) {
var child = cube.children[j];
child.material.color.setHex(cube.originalColor);
}
}
}
function highlightRow(cubes) {
for (var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
for (var j = 0; j < cube.children.length; j++) {
var child = cube.children[j];
child.material.color.setHex(0xffff00);
break;
}
}
}
Is there a way I can highlight all the cubes in a row as yellow instead of just one cube?

You need to keep your own data on which cubes are in which rows. When a cube is highlighted you need to look up the row its in and highlight the other cubes in the row
---pseudo code---
INTERSECTED = intersects[ index ].object;
row = getRowObjectIsIn(INTERSECTED)
for each object in row
highlight object

Related

how can i make a cube with a grid in three.js

Cube
I want to make something exactly like this but I can change the amount of cubes in the grid with a variable.(I have no idea how to start)
You will need to add the cubes to a Group, then add that Group to a scene, then centre the Group
Here is one approach of doing this:
const grid = new THREE.Group();
const cubeSize = 0.25;
const rows = 4;
const cols = 4;
const gap = 0.01;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
for (let z = 0; z < rows; z++) {
const cube = createCube(cubeSize);
const pos = ((cubeSize / 2) * rows) / 2 + gap;
const x = pos * row;
const y = pos * col;
cube.position.set(x, y, pos * z);
grid.add(cube);
}
}
}
scene.add(grid);
Note, this won't scale well the more cubes you add. Since the the total number of objects will be (rows + cols) ^ 3, which will produce a large number of objects. In light of this, you can use InstancedMesh mesh, which I have shown a demo of below.
Demo:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<script type="module">
import * as THREE from "https://cdn.jsdelivr.net/npm/three#0.121.1/build/three.module.js";
import { OrbitControls } from "https://cdn.jsdelivr.net/npm/three#0.121.1/examples/jsm/controls/OrbitControls.js";
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const controls = new OrbitControls(camera, renderer.domElement);
const grid = new THREE.Group();
const cubeSize = 0.25;
const size = 20;
const gap = 0.01;
const geometry = new THREE.BoxBufferGeometry(
cubeSize,
cubeSize,
cubeSize
);
const material = new THREE.MeshNormalMaterial();
const cubes = new THREE.InstancedMesh(
geometry,
material,
Math.pow(size, 3)
);
cubes.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
grid.add(cubes);
scene.add(grid);
const cube = new THREE.Object3D();
const center = (size + gap * (size - 1)) * -0.5;
grid.position.set(center, center, center);
camera.position.z = size * 1.5;
(function animate() {
requestAnimationFrame(animate);
let i = 0;
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
for (let z = 0; z < size; z++) {
cube.position.set(x, y, z);
cube.updateMatrix();
cubes.setMatrixAt(i, cube.matrix);
i++;
}
}
}
cubes.instanceMatrix.needsUpdate = true;
controls.update();
renderer.render(scene, camera);
})();
</script>

how to check dynamically changing boolean value using three js

I'm making a 3D 4x4x4 tic tac toe with three js, and to check win combo condition, I created a boolean array. Since there are 16*4=64 blocks, I made a boolean array of size 64 and set it to false by default. And then whenever the user clicks one of the blocks it changes the clicked object to true dynamically.
To check the horizontal win condition, i used this,
var camera, scene, renderer, mesh, material, controls;
var targetList = [];
var targetListBool = new Array(64).fill(false);
console.log(targetListBool);
// var projector, mouse = { x: 0, y: 0 };
var projecter;
var mouse = new THREE.Vector2(),
INTERSECTED;
init();
animate();
addCubes();
render();
function addCubes() {
var xDistance = 30;
var zDistance = 15;
var geometry = new THREE.BoxBufferGeometry(10, 10, 10);
var material = new THREE.MeshBasicMaterial({
color: 0x6C70A8
});
//initial offset so does not start in middle.
var xOffset = -80;
//1
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0xadc9f4
}));
mesh.position.x = (xDistance * (i)) + xOffset;
mesh.position.z = (zDistance * (j));
scene.add(mesh);
targetList.push(mesh);
}
//2
for (let j = 0; j < 4; j++) {
var mesh2 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0xadc9f4
}));
mesh2.position.x = (xDistance * (i)) + xOffset;
mesh2.position.z = (zDistance * (j));
mesh2.position.y = 15;
scene.add(mesh2);
targetList.push(mesh2);
}
//3
for (let j = 0; j < 4; j++) {
var mesh3 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0xadc9f4
}));
mesh3.position.x = (xDistance * (i)) + xOffset;
mesh3.position.z = (zDistance * (j));
mesh3.position.y = 30;
scene.add(mesh3);
targetList.push(mesh3);
}
//4
for (let j = 0; j < 4; j++) {
var mesh4 = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: 0xadc9f4
}));
mesh4.position.x = (xDistance * (i)) + xOffset;
mesh4.position.z = (zDistance * (j));
mesh4.position.y = 45;
scene.add(mesh4);
targetList.push(mesh4);
}
}
for (var i = 0; i < targetList.length; i++) {
targetList[i].name = i;
}
}
function init() {
// Renderer.
renderer = new THREE.WebGLRenderer({
antialias: true
});
// renderer = new THREE.WebGLRenderer();
//renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// Add renderer to page
document.body.appendChild(renderer.domElement);
// Create camera.
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 150;
// Add controls
controls = new THREE.TrackballControls(camera);
controls.addEventListener('change', render);
controls.target.set(0, 0, -50);
// Create scene.
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
// Create directional light and add to scene.
var pointLight = new THREE.PointLight(0xFFFFFF, 1, 100000);
pointLight.position.set(1, 1, 1).normalize();
scene.add(pointLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Add listener for window resize.
window.addEventListener('resize', onWindowResize, false);
}
// initialize object to perform world/screen calculations
projector = new THREE.Projector();
// when the mouse moves, call the given function
document.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
event.preventDefault();
console.log("Click.");
// update the mouse variable
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// find intersections
// create a Ray with origin at the mouse position
// and direction into the scene (camera direction)
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
projector.unprojectVector(vector, camera);
var ray = new THREE.Raycaster();
ray.setFromCamera(mouse, camera);
// create an array containing all objects in the scene with which the ray intersects
var intersects = ray.intersectObjects(targetList);
// if there is one (or more) intersections
if (intersects.length > 0 && INTERSECTED != intersects[0].object) {
INTERSECTED = intersects[0].object;
INTERSECTED.material.emissive.setHex(0xff0000);
console.log(INTERSECTED.name);
// console.log("Hit # " + toString( intersects[0].point ) );
// change the color of the closest face.
// intersects[ 0 ].face.color.setHex(0xffa500);
// intersects[ 0 ].object.geometry.colorsNeedUpdate = true;
for (var i = 0; i < targetList.length; i++) {
if (INTERSECTED.name == i) {
targetListBool[i] = true;
}
}
console.log(targetListBool);
}
}
// $(intersec).click(function(){
// alert('you clicked number 1 block');
// });
function toString(v) {
return "[ " + v.x + ", " + v.y + ", " + v.z + " ]";
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
}
function render() {
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
controls.handleResize();
}
for (let i = 0; i <targetListBool.length ; i+=4) {
if(targetListBool[i]
&&targetListBool[i+1]
&&targetListBool[i+2]
&&targetListBool[i+3]){
alert('win');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tic tac toe</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
.info {
position: absolute;
background-color: black;
opacity: 0.8;
color: white;
text-align: center;
top: 0px;
width: 100%;
}
.info a {
color: #00ffff;
}
button {
display: hidden;
}
</style>
</head>
<body>
<div id="container">
<div>
<!-- <button id="restart">Restart</button> -->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/controls/TrackballControls.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/utils/BufferGeometryUtils.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/libs/dat.gui.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/renderers/Projector.js"></script>
</body>
</html>
I'm trying to check just horizontal win combination for a starter now.
for (let i = 0; i <targetListBool.length ; i+=4) {
if(targetListBool[i]
&&targetListBool[i+1]
&&targetListBool[i+2]
&&targetListBool[i+3]){
alert('win');
}
}
But it doesn't know that some values have changed by click event earier.
Just to clarify, it's supposed to alert 'win' if 4 consecutive horizontal blocks are clicked in each plane. but I guess something's wrong with the if statement in the for loop at the end of the snippet.
It's my first time using three js and i'm not really familiar with javaScript either. I would appreciate any help. Thanks.
Your system wins if it has 4 in a row on either the x,y or z axis. Your function only check the booleans in one direction. So best is to track the data in a 3 dimensional way. Here is an example of it. I manually set 4 on a row on the z axis and then do the check.
The check could and should be improved though. It's pretty inefficient, but kept it easy for the example and because I don't know your exact intentions. Should diagonals be checked too for example?
//Fill a variable with x,y,z coordinates with a boolean value that is false.
var locations = {};
for (var x = 1; x <= 4; x++) {
locations[x] = {};
for (var y = 1; y <= 4; y++) {
locations[x][y] = {};
for (var z = 1; z <= 4; z++) {
locations[x][y][z] = false;
}
}
}
//Set 4 values on the X axis to true for testing
locations[1][2][3] = true;
locations[2][2][3] = true;
locations[3][2][3] = true;
locations[4][2][3] = true;
//Set 4 values on the Z axis to true for testing
locations[1][2][1] = true;
locations[1][2][2] = true;
locations[1][2][3] = true;
locations[1][2][4] = true;
//Test if there are 4 on a row - note this can be done more efficient with a bit more thought and does not work for diagonals
var winX = false;
var winY = false;
var winZ = false;
for (var x = 1; x <= 4; x++) {
for (var y = 1; y <= 4; y++) {
for (var z = 1; z <= 4; z++) {
if(locations[x][y][z]) {
//check X for current position
if(locations[1][y][z] && locations[2][y][z] && locations[3][y][z] && locations[4][y][z]) {
winX = true;
}
//check Y for current position
if(locations[x][1][z] && locations[x][2][z] && locations[x][3][z] && locations[x][4][z]) {
winY = true;
}
//check Z for current position
if(locations[x][y][1] && locations[x][y][2] && locations[x][y][3] && locations[x][y][4]) {
winZ = true;
}
}
}
}
}
//Log the results, should return true for X and Z and false for Y
console.log("Win X: " + winX);
console.log("Win Y: " + winY);
console.log("Win Z: " + winZ);

Pins position for Cloth in Three.js

Can someone help! I am simulating a cloth attached to their 4 corners. I am trying to re-locate the 4 pins 0, 10, 88, 98 of the Cloth with an 10x10 array. I want to be able to place each Pin at a different position in x,y,z.
For this simulation I am using Three.js and Cloth.js.
Something similar to this example:
[https://threejs.org/examples/#webgl_animation_cloth][1]
Here is my Code and also the Cloth code I am using.
var pinsFormation = [];
pinsFormation.push( pins );
pins = [ 0, 10, 88, 98 ];
var container, stats;
var camera, scene, renderer, clothGeometry, object;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xFFFFFF );
camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 1000, 50, 1000 );
// cloth
var material_wire = new THREE.MeshBasicMaterial( { color : 0x000000, side: THREE.DoubleSide, wireframe: true } );
clothGeometry = new THREE.ParametricGeometry( clothFunction, cloth.w, cloth.h );
object = new THREE.Mesh( clothGeometry, material_wire ); // clothMaterial
object.position.set( 0, 0, 0 );
scene.add( object );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.maxPolarAngle = Math.PI * 1.5;
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
var time = Date.now();
var windStrength = Math.cos( time / 7000 ) * 20 + 40;
windForce.set( Math.sin( time / 2000 ), Math.cos( time / 3000 ), Math.sin( time / 1000 ) )
windForce.normalize()
windForce.multiplyScalar( windStrength );
simulate( time );
render();
}
function render() {
var p = cloth.particles;
for ( var i = 0, il = p.length; i < il; i ++ ) {
clothGeometry.vertices[ i ].copy( p[ i ].position );
}
clothGeometry.verticesNeedUpdate = true;
clothGeometry.computeFaceNormals();
clothGeometry.computeVertexNormals();
renderer.render( scene, camera );
}
// cloth.js
var DAMPING = 0.03;
var DRAG = 1 - DAMPING;
var MASS = 0.1;
var restDistance = 25;
var xSegs = 10;
var ySegs = 10;
var clothFunction = plane( restDistance * xSegs, restDistance * ySegs );
var cloth = new Cloth( xSegs, ySegs );
var GRAVITY = 981 * 1.4;
var gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
var TIMESTEP = 18 / 1000;
var TIMESTEP_SQ = TIMESTEP * TIMESTEP;
var pins = [];
var wind = true;
var windStrength = 2;
var windForce = new THREE.Vector3( 0, 0, 0 );
var tmpForce = new THREE.Vector3();
var lastTime;
function plane( width, height ) {
return function( u, v ) {
var x = ( u - 0.5 ) * width;
var y = ( v - 0.1 ) * height;
var z = 0;
return new THREE.Vector3( x, y, z );
};
}
function Particle( x, y, z, mass ) {
this.position = clothFunction( x, y ); // position
this.previous = clothFunction( x, y ); // previous
this.original = clothFunction( x, y );
this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
this.mass = mass;
this.invMass = 1 / mass;
this.tmp = new THREE.Vector3();
this.tmp2 = new THREE.Vector3();
}
// Force -> Acceleration
Particle.prototype.addForce = function( force ) {
this.a.add(
this.tmp2.copy( force ).multiplyScalar( this.invMass )
);
};
// Performs Verlet integration
Particle.prototype.integrate = function( timesq ) {
var newPos = this.tmp.subVectors( this.position, this.previous );
newPos.multiplyScalar( DRAG ).add( this.position );
newPos.add( this.a.multiplyScalar( timesq ) );
this.tmp = this.previous;
this.previous = this.position;
this.position = newPos;
this.a.set( 0, 0, 0 );
};
var diff = new THREE.Vector3();
function satisfyConstraints( p1, p2, distance ) {
diff.subVectors( p2.position, p1.position );
var currentDist = diff.length();
if ( currentDist === 0 ) return;
var correction = diff.multiplyScalar( 1 - distance / currentDist );
var correctionHalf = correction.multiplyScalar( 0.5 );
p1.position.add( correctionHalf );
p2.position.sub( correctionHalf );
}
function Cloth( w, h ) {
w = w || 20;
h = h || 20;
this.w = w;
this.h = h;
var particles = [];
var constraints = [];
var u, v;
// Create particles
for ( v = 0; v <= h; v ++ ) {
for ( u = 0; u <= w; u ++ ) {
particles.push(
new Particle( u / w, v / h, 0, MASS )
);
}
}
// Structural
for ( v = 0; v < h; v ++ ) {
for ( u = 0; u < w; u ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u, v + 1 ) ],
restDistance
] );
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u + 1, v ) ],
restDistance
] );
}
}
for ( u = w, v = 0; v < h; v ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u, v + 1 ) ],
restDistance
] );
}
for ( v = h, u = 0; u < w; u ++ ) {
constraints.push( [
particles[ index( u, v ) ],
particles[ index( u + 1, v ) ],
restDistance
] );
}
this.particles = particles;
this.constraints = constraints;
function index( u, v ) {
return u + v * ( w + 1 );
}
this.index = index;
}
function simulate( time ) {
if ( ! lastTime ) {
lastTime = time;
return;
}
var i, il, particles, particle, pt, constraints, constraint;
// Aerodynamics forces
if ( wind ) {
var face, faces = clothGeometry.faces, normal;
particles = cloth.particles;
for ( i = 0, il = faces.length; i < il; i ++ ) {
face = faces[ i ];
normal = face.normal;
tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
particles[ face.a ].addForce( tmpForce );
particles[ face.b ].addForce( tmpForce );
particles[ face.c ].addForce( tmpForce );
}
}
for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
particle = particles[ i ];
particle.addForce( gravity );
particle.integrate( TIMESTEP_SQ );
}
// Start Constraints
constraints = cloth.constraints;
il = constraints.length;
for ( i = 0; i < il; i ++ ) {
constraint = constraints[ i ];
satisfyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
}
// Pin Constraints
for ( i = 0, il = pins.length; i < il; i ++ ) {
var xy = pins[ i ];
var p = particles[ xy ];
p.position.copy( particles.original );
p.previous.copy( particles.original );
}
}
The "pin" is just the index of one of the vertices.. so what you'll have to do is identify the vertex corresponding to the spot you want to pin.. you can get that from a raycast when the user clicks the mesh, or figure it our analytically.

THREE.js smooth material color cycle in separate geometries

guys!
Look at the codepen provided. Multiple curves animation.
So i'm trying to reach this smooth hue change at every drawn curve.
The color of every next curve should be shifted in hue a bit.
And i need to control the duration of this shifting.
Right now the colors shift seem random and i cant control it's duration.
Need your help. Thanks.
'use strict';
var camera, scene, renderer, controls;
var params = {P0x: 0, P0y: 0,P1x: 0.6, P1y: 1.7,P2x: -0.1, P2y: 1.1,P3x: 0, P3y: 3,steps: 30};
var controlPoints = [[params.P0x, params.P0y, 0],[params.P1x, params.P1y, 0],[params.P2x, params.P2y, 0],[params.P3x, params.P3y, 0]];
var material = new THREE.LineBasicMaterial( { color: 0xd9e2ec, linewidth: 1 } );
var mat = new THREE.MeshBasicMaterial({wireframe:true,color: 0x4a4a4a, side: THREE.DoubleSide, opacity:0, transparent:true});
var angle1 = 0;
var angle2 = 0;
var color = 0;
var initialCurvesCount = 5;
var initialGroupsCount = 6;
var curveQuality = 500;
var hColor = 1;
var mesh = {};
var axis1 = new THREE.Vector3(0,0.8,1.2);
var axis2 = new THREE.Vector3(0,-0.8,3.2);
var geom = {};
var curveGeometry;
var curves;
var group = {};
var triangle = [[ 0, 0.5, -0.5, 0 ], [ 0.6, -0.5, -0.5, 0.6 ], [ 0, 0, 0, 0 ]];
init();
createCurveGroups();
createHelpers();
animate();
function createHelpers() {
// var gridHelper = new THREE.GridHelper( 4, 8, 0xadd6e8, 0xdddddd );
// var gridHelper2 = new THREE.GridHelper( 4, 8, 0xadd6e8, 0xdddddd );
// gridHelper2.rotation.x = 1.58;
// gridHelper.position.y = 0;
// gridHelper.position.x = 0;
//
// var axisHelper = new THREE.AxisHelper( 1 );
// axisHelper.position.y = 0;
// axisHelper.position.x = 0;
//
// scene.add( gridHelper );
// scene.add( gridHelper2 );
// scene.add( axisHelper );
}
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.set(-0,0,2);
camera.rotation.y = -0;
camera.frustumCulled = false;
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0xffffff, 1 );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function createBezierCurveNEW(cpList, steps) {
var N = Math.round(steps)+1 || 20;
var geometry = new THREE.Geometry();
var curve = new THREE.CubicBezierCurve3();
var cp = cpList[0];
curve.v0 = new THREE.Vector3(cp[0], cp[1], cp[2]);
cp = cpList[1];
curve.v1 = new THREE.Vector3(cp[0], cp[1], cp[2]);
cp = cpList[2];
curve.v2 = new THREE.Vector3(cp[0], cp[1], cp[2]);
cp = cpList[3];
curve.v3 = new THREE.Vector3(cp[0], cp[1], cp[2]);
var j, stepSize = 1/(N-1);
for (j = 0; j < N; j++) {
geometry.vertices.push( curve.getPoint(j * stepSize) );
}
return geometry;
};
function createTriangle(number) {
geom[number] = new THREE.Geometry();
geom[number].vertices.push(new THREE.Vector3(0, 0.35, 0));
geom[number].vertices.push(new THREE.Vector3(0.35, -0.35, 0));
geom[number].vertices.push(new THREE.Vector3(-0.35,-0.35, 0));
geom[number].faces.push(new THREE.Face3(0, 1, 2));
geom[number].applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0, 0 ) );
mesh[number] = new THREE.Mesh(geom[number], mat);
};
function createCurveGroups() {
for ( var i = 1; i <= initialGroupsCount; ++i ) {
group[i] = new THREE.Group();
scene.add( group[i] );
group[i].rotation.set( 0, 3.15, i/((initialGroupsCount/6 - initialGroupsCount/130)) );
};
};
function cloneCurvesToGroups() {
for ( var i = 1; i <= (Object.keys(group).length); ++i ) {
var curvesArray = {};
curvesArray[i] = curves.clone();
group[i].add(curvesArray[i]);
}
};
function colorChanger() {
}
function morphTriangle() {
group[1].add( mesh[1] );
mesh[1].rotateOnAxis(axis1,(angle2 + 1));
mesh[1].updateMatrix();
mesh[1].geometry.applyMatrix( mesh[1].matrix );
mesh[1].matrix.identity();
mesh[1].position.set( 0, 0, 0 );
mesh[1].geometry.verticesNeedUpdate = true;
group[1].add( mesh[2] );
mesh[2].rotateOnAxis(axis2,-angle2);
mesh[2].updateMatrix();
mesh[2].geometry.applyMatrix( mesh[2].matrix );
mesh[2].matrix.identity();
mesh[2].position.set( 0, 0, 0 );
mesh[2].geometry.verticesNeedUpdate = true;
};
function changeCreatedCurves() {
angle1 += 0.00450;
angle2 += 0.0020;
createTriangle(1);
createTriangle(2);
morphTriangle();
for ( var i = 1; i <= initialCurvesCount; ++i ) {
controlPoints[0][0] = -0.09 ;
controlPoints[0][1] = 0;
controlPoints[0][2] = -0.035 + i/10000; //optional + Math.sin(angle1)/6;
controlPoints[2][0] = mesh[2].geometry.vertices[0]['x'] + 0.1 - i/55 + Math.cos(angle1)/6;
controlPoints[2][1] = mesh[2].geometry.vertices[0]['y'];
controlPoints[2][2] = mesh[2].geometry.vertices[0]['z'] + i/20 + Math.sin(angle1)/6;
controlPoints[1][0] = mesh[1].geometry.vertices[0]['x'] - i/20 + Math.sin(angle1)/6;
controlPoints[1][1] = mesh[1].geometry.vertices[0]['y'];
controlPoints[1][2] = mesh[1].geometry.vertices[0]['z'] - i/20 + Math.sin(angle1)/6;
controlPoints[3][0] = triangle[0][0] - 0.05 + i/10;
controlPoints[3][1] = triangle[1][0] - 0.05 + i/10;
controlPoints[3][2] = triangle[2][0];
// !!! HERE IS THE PROBLEM !!!
hColor = hColor + i*0.3;
var wow = String("hsl(" + hColor*i + "," + 100 + "%" + "," + 70 + "%" + ")");
// console.log(wow)
// console.log("this is i "+ i);
material = new THREE.LineBasicMaterial( { color: wow, linewidth: 1 } );
// !!! HERE IS THE PROBLEM !!!
curveGeometry = createBezierCurveNEW(controlPoints, (curveQuality/initialGroupsCount));
curves = new THREE.Line(curveGeometry, material);
group[1].add(curves);
// debugger
render();
cloneCurvesToGroups();
}
};
function disposeCurveGeometry() {
for (var i = 0; i <= group[1].children.length; ++i) {
group[1].children[0].geometry.dispose();
group[1].children[0].material.dispose();
for (var j = 1; j <= (Object.keys(group).length); ++j) {
group[j].remove(group[j].children[0]);
};
};
};
function render() {
renderer.render(scene, camera);
};
function animate() {
requestAnimationFrame(animate);
changeCreatedCurves();
disposeCurveGeometry();
onWindowResize();
};
Working example code at codepen
Is something like this what you are looking for?
var vueDifference = 20;
var speed = 0.03;
hColor = hColor + speed;
var wow = String("hsl(" + (hColor + i * vueDifference) + "," + 100 + "%" + "," + 70 + "%" + ")");

Three.js: How to animate particles along a line

I'm trying to animate particles along a path similar to this chrome expriement: http://armsglobe.chromeexperiments.com/
I've tried digging into the source of this project, and what I've groked so far is that they are using a built in curve method .getPoitns() to generate about 30 points on their lines.
Is there a better example on what I'm trying to accomplish? Is there a method for getting points on the line than using the .lerp() method 30 times to get 30 points? Should I just use TWEEN animations?
Any help or direction would be appreciated.
I've figured out a solution, not sure if it's the best or not, but it works well.
You can find a demo on JsFiddle: https://jsfiddle.net/L4beLw26/
//First create the line that we want to animate the particles along
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-800, 0, -800));
geometry.vertices.push(new THREE.Vector3(800, 0, 0));
var line = new THREE.Line(geometry, material);
var startPoint = line.geometry.vertices[0];
var endPoint = line.geometry.vertices[1];
scene.add(line);
//next create a set of about 30 animation points along the line
var animationPoints = createLinePoints(startPoint, endPoint);
//add particles to scene
for ( i = 0; i < numParticles; i ++ ) {
var desiredIndex = i / numParticles * animationPoints.length;
var rIndex = constrain(Math.floor(desiredIndex),0,animationPoints.length-1);
var particle = new THREE.Vector3();
var particle = animationPoints[rIndex].clone();
particle.moveIndex = rIndex;
particle.nextIndex = rIndex+1;
if(particle.nextIndex >= animationPoints.length )
particle.nextIndex = 0;
particle.lerpN = 0;
particle.path = animationPoints;
particleGeometry.vertices.push( particle );
}
//set particle material
var pMaterial = new THREE.ParticleBasicMaterial({
color: 0x00FF00,
size: 50,
map: THREE.ImageUtils.loadTexture(
"assets/textures/map_mask.png"
),
blending: THREE.AdditiveBlending,
transparent: true
});
var particles = new THREE.ParticleSystem( particleGeometry, pMaterial );
particles.sortParticles = true;
particles.dynamic = true;
scene.add(particles);
//update function for each particle animation
particles.update = function(){
// var time = Date.now()
for( var i in this.geometry.vertices ){
var particle = this.geometry.vertices[i];
var path = particle.path;
particle.lerpN += 0.05;
if(particle.lerpN > 1){
particle.lerpN = 0;
particle.moveIndex = particle.nextIndex;
particle.nextIndex++;
if( particle.nextIndex >= path.length ){
particle.moveIndex = 0;
particle.nextIndex = 1;
}
}
var currentPoint = path[particle.moveIndex];
var nextPoint = path[particle.nextIndex];
particle.copy( currentPoint );
particle.lerp( nextPoint, particle.lerpN );
}
this.geometry.verticesNeedUpdate = true;
};
function createLinePoints(startPoint, endPoint){
var numPoints = 30;
var returnPoints = [];
for(i=0; i <= numPoints; i ++){
var thisPoint = startPoint.clone().lerp(endPoint, i/numPoints);
returnPoints.push(thisPoint);
}
return returnPoints;
}
function constrain(v, min, max){
if( v < min )
v = min;
else
if( v > max )
v = max;
return v;
}
and then in the animation loop:
particles.update();
I don't know if anyone else can't see the snippets working, but I took the answer that jigglebilly provided and put it into a full html page and is working. Just so that if you want to see a working version. `
Particle Test
<script src="../js/three.js"></script>
<script type="text/javascript">
var renderer = new THREE.WebGLRenderer( { antialias: true } );
var camera = new THREE.PerspectiveCamera( 45, (window.innerWidth) / (window.innerHeight), 100, 10000);
var container = document.getElementById("containerElement");
var numParticles = 40;
container.appendChild( renderer.domElement );
var scene = new THREE.Scene();
var material = new THREE.LineBasicMaterial({color: 0x0000ff });
//First create the line that we want to animate the particles along
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-800, 0, -800));
geometry.vertices.push(new THREE.Vector3(800, 0, 0));
var line = new THREE.Line(geometry, material);
var startPoint = line.geometry.vertices[0];
var endPoint = line.geometry.vertices[1];
scene.add(line);
//next create a set of about 30 animation points along the line
var animationPoints = createLinePoints(startPoint, endPoint);
var particleGeometry = new THREE.Geometry();
//add particles to scene
for ( i = 0; i < numParticles; i ++ ) {
var desiredIndex = i / numParticles * animationPoints.length;
var rIndex = constrain(Math.floor(desiredIndex),0,animationPoints.length-1);
var particle = new THREE.Vector3();
var particle = animationPoints[rIndex].clone();
particle.moveIndex = rIndex;
particle.nextIndex = rIndex+1;
if(particle.nextIndex >= animationPoints.length )
particle.nextIndex = 0;
particle.lerpN = 0;
particle.path = animationPoints;
particleGeometry.vertices.push( particle );
}
//set particle material
var pMaterial = new THREE.ParticleBasicMaterial({
color: 0x00FF00,
size: 50,
blending: THREE.AdditiveBlending,
transparent: true
});
var particles = new THREE.ParticleSystem( particleGeometry, pMaterial );
particles.sortParticles = true;
particles.dynamic = true;
scene.add(particles);
function UpdateParticles(){
// var time = Date.now()
for( var i = 0; i < particles.geometry.vertices.length; i++ ){
var particle = particles.geometry.vertices[i];
var path = particle.path;
particle.lerpN += 0.05;
if(particle.lerpN > 1){
particle.lerpN = 0;
particle.moveIndex = particle.nextIndex;
particle.nextIndex++;
if( particle.nextIndex >= path.length ){
particle.moveIndex = 0;
particle.nextIndex = 1;
}
}
var currentPoint = path[particle.moveIndex];
var nextPoint = path[particle.nextIndex];
particle.copy( currentPoint );
particle.lerp( nextPoint, particle.lerpN );
}
particles.geometry.verticesNeedUpdate = true;
};
animate();
function createLinePoints(startPoint, endPoint){
var numPoints = 30;
var returnPoints = [];
for(i=0; i <= numPoints; i ++){
var thisPoint = startPoint.clone().lerp(endPoint, i/numPoints);
returnPoints.push(thisPoint);
}
return returnPoints;
}
function constrain(v, min, max){
if( v < min )
v = min;
else
if( v > max )
v = max;
return v;
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
UpdateParticles();
}
</script>
`
This uses three.js R67.

Categories

Resources