What are the best methods for assigning different characteristics to cubes using three.js?

Hello! I am currently working on a project using three.js. My goal is to create four cubes and achieve the following tasks: (1) apply a texture from another image onto one cube, (2) make light reflect off of a specific cube, and (3) make one cube transparent. I have been facing some challenges with loading the texture onto the cube and understanding how to make the light reflect properly. However, I believe I have successfully achieved the transparency effect. Any help or guidance on this would be greatly appreciated.

Below is the code that I have written so far:

//declare variables
var scene;
var renderer;
var mesh, newMesh;

init();
animate();

//function to create 4 cubes

function init() {

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000);

    var light = new THREE.DirectionalLight( 0xffffff );
    light.position.set( 0, 1, 1 ).normalize();
    scene.add(light);

    var geometry = new THREE.CubeGeometry( 10, 10, 10);
    var material = new THREE.MeshLambertMaterial({color: 0x0033ff , transparent: true, opacity: 0.5});

    // position the cubes and add textures

    mesh = new THREE.Mesh(geometry, material );
    mesh.position.z = -50;
    scene.add( mesh );

    newMesh = mesh.clone();
    newMesh.material =new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x0033ff, specular: 0x555555, shininess: 70} );
    newMesh.position.x = 50;
    scene.add(newMesh);

    newMesh2 = mesh.clone();
    newMesh2.material =new THREE.MeshLambertMaterial({color: 0x0033ff});
    newMesh2.position.y = -25;
    scene.add(newMesh2);

    newMesh3 = mesh.clone();
    var loader = new THREE.TextureLoader();
//    loader.load("http://www.photoshoptextures.com/sky-textures/blue-sky-texture.jpg",, function(texture) {
//      newMesh3.material = new THREE.MeshLambertMaterial({map: texture});
    newMesh3.position.x =30 ;
    scene.add(newMesh3) ;


    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    window.addEventListener( 'resize', onWindowResize, false );

    render();
}

// rotation animation for better view

function animate() {
    mesh.rotation.x += .04;
    mesh.rotation.y += .02;
    newMesh.rotation.y += .04;
    newMesh.rotation.z += .02;
   newMesh2.rotation.y += .04;
    newMesh2.rotation.z += .02;
    newMesh3.rotation.y += .04;
    newMesh3.rotation.z += .02;


    render();
    requestAnimationFrame( animate );
}

// rendering function

function render() {
    renderer.render( scene, camera );
}

// adjust camera for window resize

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}

Answer №1

Regarding textures - The process begins by creating a loader using the following code:

var loader = new THREE.TextureLoader();
. However, this loader is not utilized in the subsequent code. Remember that commented-out code does not get executed. Additionally, there are two superfluous commas before defining the callback function, which may result in the onError function being triggered instead of onLoad.

If you ever have queries regarding THREEjs, it is recommended to consult the official documentation first.

For more detailed information, refer to this specific section.

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

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Error found in the HTML tag data when viewing the page source for an issue

I am displaying some data from my express to ejs in HTML tag format. It appears correctly on the ejs template page and the web page. However, when I check the page source, the HTML tags are encoded and displayed as unescaped characters. Is there a solution ...

Any tips on making Angular 8's sort table function seamlessly integrate with data retrieved from Firebase?

I am currently working on an angular PWA project that utilizes a material table to display data from Firebase. The data is being shown properly and the paginator is functioning as expected. However, I am facing an issue with sorting the data using mat-sort ...

Vue Router Issue: Unable to Navigate to Different Routes, Always Redirected to Home Page

I am currently working on a Vue 3 project and am facing an issue with the Vue Router not displaying the correct routes. Whenever I try to navigate to routes such as /cars or /admin, the URL does not update and the application stays on the home page. import ...

What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store: const app = new Vue({ router, store, mounted: function() { var that = this; $.get("/initial_data/", {}, function(data) { that.$s ...

What is the best way to display data from an object with changing properties in React.js?

Dealing with dynamic properties in an object can be tricky, especially when trying to output the data. I encountered this issue while working with an array of objects fetched from an API call. The array contains an object named languages, and its key value ...

Prevent scrolling/touchmove events on mobile Safari under certain conditions

iOS 5 now supports native overflow: scroll functionality. I am trying to implement a feature where the touchmove event is disabled for elements that do not have the 'scrollable' class or their children. However, I am having trouble implementing ...

Choose an item within a Fabricjs canvas based on its coordinates using code

I've been struggling with this issue for quite some time. Currently, I am utilizing a Fabricjs canvas as a texture for a 3D model in Three.js. Each time there is a change on the canvas, the model renders it as a texture. My goal is to be able to cli ...

Refreshing an array in Javascript

I'm utilizing ajax to retrieve data from a database and using the DOM to generate the HTML for a compact weather widget. Within this process, I have an Array of elements called _weather. While it populates correctly, I'm encountering difficulti ...

Is it possible to reset the selectbox after removing options using Javascript/jQuery?

When I run the command below in a loop: $("#day option:last").remove(); If this command is executed multiple times, some options are missing from my selectbox. Therefore, I am looking for a way to reset the selectbox back to its original state at the be ...

Error: Unable to access attributes of an unknown variable (retrieving 'use')

I encountered an issue (TypeError: Cannot read properties of undefined (reading 'use')) while trying to execute the 'node server.js' command in the Terminal. The error points to my auth.routes.js file. https://i.sstatic.net/NQ5XL.png ...

Managing an indefinite amount of values within a PHP script

When submitting the data form, there will be a range of 10 to 100 values to be sent to the PHP file. The quantity of inputs is stored in a JavaScript function variable named count, but I am unsure of how to pass this value to the PHP file. One approach I ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Struggling to halt the continuous motion

Trying to create a typewriting effect using HTML5 has been quite the challenge. To bring it all together, I've turned to the pixi.js plugin. While I have managed to get it partly working, it appears that the update() method responsible for updating t ...

A step-by-step guide to loading a .php file via Ajax using JQuery when an item is selected from a dropdown

I have successfully populated a dropdown list using PHP from a database on the page named admin.php. Now, I am utilizing JQuery with Ajax functionality to display information when a surname is clicked from the dropdown menu. The goal is to call employerP ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Guide on generating a fresh array of objects that encompass distinct items, alongside their combined prices and quantities using JavaScript

I am struggling to generate a new array of objects from one that contains duplicates. For instance, here is the console.log output of the current array: console.log(items); [{ _id: 5eb2f7efb5b8fa62bcd7db94, workName: 'best item ever', ...

difficulty encountered when using the Angular delete method in conjunction with Express.js

I am trying to send a delete request to my Express server from Angular. remove: function (id) { return $http({ method: 'DELETE', url: '/users/delete/'+ id }) } In my Expr ...

What is the best way to integrate AJAX with draggable columns in a Laravel application?

I have successfully integrated draggable functionality for table columns using jQuery Sortable within my Laravel application. I am now facing the challenge of updating the database with the data from these columns through AJAX. Despite researching online ...