What is the best way to alter the color of faces in three.js?

I'm currently working with a sample script that involves flying bird objects. However, I am struggling to figure out how to change the color of the birds. I attempted to modify the color on the line where the birds are instantiated:

bird = birds[i] = new THREE.Mesh(new Bird(), new THREE.MeshBasicMaterial({color: 0x54A1D8, side: THREE.DoubleSide}));

Unfortunately, the color did not change...

Bird.js

 var Bird = function () {

var scope = this;

THREE.Geometry.call(this);

v(5, 0, 0);
v(-5, -2, 1);
v(-5, 0, 0);
v(-5, -2, -1);

v(0, 2, -6);
v(0, 2, 6);
v(2, 0, 0);
v(-3, 0, 0);

f3(0, 2, 1);
// f3( 0, 3, 2 );

f3(4, 7, 6);
f3(5, 6, 7);

this.computeCentroids();
this.computeFaceNormals();

function v(x, y, z) {

scope.vertices.push(new THREE.Vector3(x, y, z));

}

function f3(a, b, c) {

scope.faces.push(new THREE.Face3(a, b, c));

}

}

Bird.prototype = Object.create(THREE.Geometry.prototype);

Main script

<script>

var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight,
SCREEN_WIDTH_HALF = SCREEN_WIDTH / 2,
SCREEN_HEIGHT_HALF = SCREEN_HEIGHT / 2;

var camera, scene, renderer,
birds, bird;

var boid, boids;

var stats;

init();
animate();

function init() {

camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.z = 450;

scene = new THREE.Scene();

birds = [];
boids = [];

for (var i = 0; i < 200; i++) {

boid = boids[i] = new Boid();
boid.position.x = Math.random() * 400 - 200;
boid.position.y = Math.random() * 400 - 200;
boid.position.z = Math.random() * 400 - 200;
boid.velocity.x = Math.random() * 2 - 1;
boid.velocity.y = Math.random() * 2 - 1;
boid.velocity.z = Math.random() * 2 - 1;
boid.setAvoidWalls(true);
boid.setWorldSize(500, 500, 400);

bird = birds[i] = new THREE.Mesh(new Bird(), new THREE.MeshBasicMaterial({color: 0x54A1D8, side: THREE.DoubleSide}));
bird.phase = Math.floor(Math.random() * 62.83);
bird.position = boids[i].position;
scene.add(bird);


}

renderer = new THREE.CanvasRenderer();
// renderer.autoClear = false;
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
document.addEventListener('click', triggerPlay, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.body.appendChild(renderer.domElement);

/*stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';

document.getElementById('container').appendChild(stats.domElement);

//

window.addEventListener('resize', onWindowResize, false);
*/
}

function onWindowResize() {

camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();

renderer.setSize(window.innerWidth, window.innerHeight);

}

function onDocumentMouseMove(event) {

var vector = new THREE.Vector3(event.clientX - SCREEN_WIDTH_HALF, -event.clientY + SCREEN_HEIGHT_HALF, 0);

for (var i = 0, il = boids.length; i < il; i++) {

boid = boids[i];

vector.z = boid.position.z;

boid.repulse(vector);

}

}

//

function animate() {

requestAnimationFrame(animate);

render();
//stats.update();

}

function render() {

for (var i = 0, il = birds.length; i < il; i++) {

boid = boids[i];
boid.run(boids);

bird = birds[i];

color = bird.material.color;
color.r = color.g = color.b = (500 - bird.position.z) / 1000;

bird.rotation.y = Math.atan2(-boid.velocity.z, boid.velocity.x);
bird.rotation.z = Math.asin(boid.velocity.y / boid.velocity.length());

bird.phase = (bird.phase + (Math.max(0, bird.rotation.z) + 0.1)) % 62.83;
bird.geometry.vertices[5].y = bird.geometry.vertices[4].y = Math.sin(bird.phase) * 5;

}

renderer.render(scene, camera);

}

</script>

Answer №1

A unique style is created by dynamically adjusting the color in the rendering process to provide a fog-like effect.

selectedColor = parrot.material.selectedColor;
selectedColor.red = selectedColor.green = selectedColor.blue = ( 500 - parrot.position.z ) / 1000;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Assigning an array of objects within an AJAX request

I have a MediaObject object that includes: a Media object an array and a function called getMedia() When attempting to create a Media object and push it into the array inside the getMedia function after making an AJAX call, I encountered issues referenc ...

Response is sent by Sequelize Foreach loop before data is updated

My goal is to retrieve all content and media from a post, then append it to a new post before sending it as a response for easier access to the data. The issue I'm encountering is that the response is being sent before the content and media are fetche ...

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

Encountering a three.js issue while generating a large number of point lights

//////twinkling stars for (let index = 0; index < 1000; index++) { const stargeometry = new THREE.SphereGeometry(1, 24, 24); //create star sphere size const starmaterial = new THREE.MeshStandardMaterial({ color: 0xffffff }); //define star textur ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

Can you attach a jQuery function to multiple CSS selectors at once?

Is it feasible to bind a mouseout call to two CSS selectors in order to trigger another action when the mouse moves away from both elements simultaneously? ...

Maintaining my navigation menu as you scroll through the page

I've been working on creating a website for my business but I'm facing a challenge. My goal is to have a fixed navigation bar that stays in place as people scroll down the page, similar to what you can see on this website: (where the navigat ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

Is there a way to access the Context in the _app.js file in Next.js with React?

Hey there! I'm currently working with a context provider file and _app.js file. I need to access AppContext in the _app.js file. Can anyone provide guidance on how to successfully access the AppContext within the _app.js file? I have imp ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Why are the values in my options created using the array map method empty in React?

I decided to use a for loop to generate an array containing the numbers 1 through 12 representing each month. I then attempted to utilize the map array method to create 12 options, but unfortunately they are coming up empty. Below is a snippet of the ...

Is there a way to customize the color of the like button?

I'm trying to create a Twitter-like button with an icon that changes color. When the button is clicked, it successfully changes from gray to red. But now I'm stuck on how to make it switch back from red to gray. I am currently using javascript ...

What is the best way to extract the value from a JSON URL?

Using AngularJS, I am looking to dynamically retrieve the price value from a URL's JSON data. Is this feasible? Here is the URL JSON: link Below is my controller: angular.module("myApp",['zingchart-angularjs']).controller('MainContro ...

Datagrid in AngularJS does not update filters upon refresh

Currently, I am attempting to implement name filtering with Angular JS using the following library: https://github.com/angular-data-grid/angular-data-grid.github.io. However, an issue arises when searching as the results do not refresh immediately; only up ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...

Issue encountered: Unforeseen command: POST karma

Whenever I try to run my test cases, I encounter the following error message: Error: Unexpected request: POST data/json/api.json it("should $watch value", function(){ var request = '/data/json/api.json'; $httpBackend.expectPOST(reque ...