Determine the sphere's color using the coordinate system in three.js

Is there a way to customize the color of this sphere rendered in three.js based on its coordinates? For instance, can I make the top half of the sphere red and the bottom half black?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 400);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);


camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);

    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
};

render();

Answer №1

To determine if a face of a sphere is in the top or bottom half, you can check the y-coordinate of the face's normal. If the y-coordinate is greater than 0, the face is in the top half; if not, it's in the bottom half.

https://i.sstatic.net/mrY3X.png

var sphereGeom = new THREE.SphereGeometry(5, 32, 24);
sphereGeom.faces.forEach(function(face){ // loop through faces
    if (face.normal.y > 0) // check y-coordinate of a face's normal
    face.color.setHex(0xFF0000); // set the color of the face (red)
    else
    face.color.setHex(0x000000); // set the color of the face (black)
})

var sphere = new THREE.Mesh(sphereGeom, new THREE.MeshStandardMaterial({
    vertexColors: THREE.FaceColors // use face colors
}));
scene.add(sphere);

Check out this jsfiddle example.

For more complex geometries, you can check the coordinates of vertices of faces. For example, using geometry.vertices[face.a] gives you the coordinates of the a-vertex of a face in the array of vertices.

Answer №2

Consider making the following adjustments:

Swap out "MeshNormalMaterial" for "MeshLambertMaterial"

Introduce ambient lighting

Incorporate spotlighting

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, 500 / 400, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 400);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshLambertMaterial({color: 0xffffff});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Add an ambient light
var ambientLight = new THREE.AmbientLight( 0x707070);
// Include a spot light
var directionalLight = new THREE.DirectionalLight(0xff0000,0.8);
directionalLight.position.set(-60,60,0);
scene.add( ambientLight, directionalLight);

camera.position.z = 10;
var render = function () {
    requestAnimationFrame(render);

    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
};

render();

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

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...

Modify the color of every element by applying a CSS class

I attempted to change the color of all elements in a certain class, but encountered an error: Unable to convert undefined or null to object This is the code I used: <div class="kolorek" onclick="changeColor('34495e');" style="background-c ...

Leveraging the same React component in multiple instances and streamlining requests - NextJS vs React

Currently, I'm working on a chat application using NextJS 14. Each time a message is sent or received, there is a small icon next to the chat message that represents the user who sent the message. To achieve this, I have a ChatMessageUI component tha ...

Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts. In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (. ...

Adjusting the Materui LinearProgressWithLabel progress value to reflect a custom value

Is it possible to update the progress value of Material UI's LinearProgressWithLabel component with a custom value instead of the default one? I am trying to achieve this by obtaining my desired value from the upload progress in the Axios.post method, ...

Guide on how to combine the strings retrieved from an API

I'm having trouble concatenating multiple sentences together and highlighting specific words in each sentence. Although I can successfully highlight one sentence using the code below, I haven't been able to concatenate more than one sentence: th ...

Discovering the worth of a selected radio button using JavaScript

I need to extract the value of a radio button without any validation or clicking on a button. My goal is to retrieve the live value as soon as the user changes the selected radio button. I've attempted multiple codes, but none of them have been succ ...

JQuery does not allow for changing the selection of a RadioButtonFor

I am currently working on a code that determines whether or not to display contact information. To achieve this, I am using the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor. Upon loading the page, I need to switch from t ...

What is the proper way to retrieve the value of the key "order" from this JSON object (containing semicolons in the name)?

Vijay Anand inquired about this particular matter yesterday, unfortunately, the discussion was closed before receiving any solutions: HTTP Response: { "entry": { "@xml:base": "https://API_PROC_SRV/", "@xmlns": "http://www.w3.org/2005/Atom", ...

The SetCookie header was not properly stored within the system

Currently, I am developing a web application using node/express.js for the backend API and Vue.js for the frontend. Regarding authentication, I am implementing JWT and sending the value through an HttpOnly cookie. However, despite seeing the "Set-Cookie" ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

What is the method for displaying a file using a binary string as input?

Is there a way to display a PDF file from a binary string on a web browser? I know that for image files, we can use atob() and then <img src="data:image/png;base64,... But what about PDF files? Is there an equivalent method or syntax like ReadItAs("cont ...

The function is not operational while executing addEventListener

I'm encountering some bugs in my Angular 1.5 project with TypeScript. I'm trying to retrieve the scrollTop value from the .uc-card element. public container = document.querySelector(".uc-card"); In my $onInit, I have: public $onInit() { this ...

Reactjs is displaying an AxiosError stating a Network Error

Working on a project with Reactjs and Nextjs, I encountered an issue where the data being posted with axios is inserting "NULL" values. I'm not sure where I am going wrong. Below is the code snippet in Nextjs: const userData = { name: state.name, ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

Modifying column layout within an HTML webpage

I'm seeking advice on modifying a code. I'd like to keep it the same as it is now, but with one change - I want to decrease the width of the main video box and add another one beside it with an iframe code for a chatbox. Here's the current c ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

Error occurred while making a request in React using Axios: TypeError - Unable to retrieve the 'token' property as it is undefined

After successfully receiving a token from logging in with React Redux, I attempted to authorize it using the token. However, an error occurred stating Axios request failed: TypeError: Cannot read property 'token' of undefined. The token is stored ...