Is it possible to use Three.js to generate a single mesh that can replace multiple individual objects?

Check out my latest project at this link: maison.whiteplay.fr

I'm currently working on creating a 3D PacMan game. In my code, I am using mesh to construct the level, but I'm facing performance issues due to the large number of individual bubble objects that need to be eaten by the player to win. Is it possible to optimize these bubbles using the same technology (mesh)? If so, how can I implement it?

Take a look at a snippet of my code below:

var geometrySphere = new THREE.SphereGeometry(5, 32, 32); 
var bille = function(x,z){ 
    this.bille = new THREE.Mesh(
        geometrySphere, 
        new THREE.MeshBasicMaterial({color: 0xffff00})
    );
    this.bille.position.x = (x-15.5) * 100; 
    this.bille.position.y = 100;  
    this.bille.position.z = (z-15.5) * 100; 
    scene.add(this.bille); 
}

Thank you for taking the time to read this! If you have any suggestions or tips on improving my code, feel free to share them with me :)

Answer №1

Instead of creating a new instance every time, consider reusing your materials:

var geometrySphere = new THREE.SphereGeometry( 5, 32, 32 ); 
var billeMaterial = new THREE.MeshBasicMaterial( {color: 0xffff00} );
var createBille = function(x,z){ 
    this.bille = new THREE.Mesh(
        geometrySphere, 
        billeMaterial
    );
    this.bille.position.x = (x-15.5)*100; this.bille.position.y = 100;  
    this.bille.position.z = (z-15.5)*100; scene.add(this.bille); 
}

Reusing materials can improve performance significantly.

How do you go about duplicating meshes/objects in your projects?

Answer №2

It seems like your code is very close to being correct.

For your specific situation, where you have N equal balls, you should use N meshes but only one material.

This way, if you want to colorize just one ball, you'll need to apply a new material to that ball specifically, otherwise all the balls will change color.

If you're experiencing lag, it might be due to how the spheres are constructed.

It appears that you copied and pasted from the documentation without actually reading it.

var geometrySphere = new THREE.SphereGeometry( 5, 32, 32 );

According to the documentation:

radius — sphere radius. Default is 50.
widthSegments — number of horizontal segments. Minimum value is 3, default is 8.
heightSegments — number of vertical segments. Minimum value is 2, default is 6.

Having 32 * 32 segments for your small, single-color bubbles doesn't make sense.

The higher these values are, the more complex it is to draw each frame.

I recommend creating spheres with fewer vertical/horizontal segments (e.g., 8*8).

Check out this demo.

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

Encountering issues when attempting to store images with node.js

Currently, I am attempting to obtain an image from wikimedia with the following link: upload.wikimedia.org/wikipedia/commons/thumb/e/e3/AybükeArslan_(3).JPG/220px-AybükeArslan_(3).JPG Unfortunately, when using node.js to retrieve the image, the wikimed ...

The error message "TypeError: res.response is undefined" is indicating

Currently, I am implementing user authentication using JWT auth within a Vue/Laravel single-page application. The problem arises in the register module as it fails to respond upon clicking the button. Upon inspecting the Firefox developer edition's co ...

There was an error with validation in Graphql that was of an undefined type

Running a gql query on a React app with default variables is causing an error. The specific error message is: Error: GraphQL error: Validation error of type FieldUndefined: Field 'firstname' in type 'HealthcareWorkersPage' is undefin ...

Vite is turning a blind eye to compiler errors until the specific file is executed during runtime

There's an odd issue with Vite that allows me to log in to my app and use it freely, until I click on a page that triggers a compilation error. Once that happens, the page won't render and the error is displayed in the console. Strangely enough, ...

Best practices for securing string values in Node.js

Looking to retrieve the IP address with nodejs/express. Check out the code snippet below that accomplishes this: const ipAddress = String(req.ip || "unknown"); Considering that req.ip is pulled from an HTTP header, there's a potential risk ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

Why is the text returned by the Angular Response body missing the JSON brackets? Strange, isn't it

As a newcomer to Angular 2, I should mention that some information is internal and will be replaced with placeholders when needed. My current task involves making a simple post request and retrieving the contents of the request body. Below is my existing ...

Using whitespace to format a document.write in JavaScript

I'm in the process of creating a dynamic table using JavaScript and a set of objects. I've managed to structure it, but now I require some extra white space between them, almost like tabbing them out. How can I achieve this efficiently with my cu ...

Increasing Asynchronous Capabilities with Dynamically Updating jQuery Deferred within then() Method

I am currently exploring the functionalities of jQuery Deferred and I have encountered a challenge regarding chaining multiple deferreds. Let me outline my simplified issue: var def1 = $.ajax(...); // executing ajax call 1 var def2 = null, def3 = null; $ ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

Tips for making a horizontal grid layout with three items in each row

I have a scenario where I need to render a group of Player components using map() loop, and I want them to be displayed horizontally side by side using a Grid component from material-ui. Currently, the components are rendering in a vertical layout: https ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

The Firebase transaction encountered a null value during reading, despite there being data present at the specified path

After working with Firebase transactions for some time, I've come to understand that occasionally the data read can be null until it is obtained from the server and committed. However, I am encountering a peculiar scenario where the transaction reads ...

Simple method to retrieve the ID of an input field within a form using jQuery selectors

I have a form with each input field having a unique id, and I have attached a jQuery 'input' event to the form. I want to retrieve the id of the field on which the user changes some value using a jQuery function. There seems to be something missi ...

Data not being properly transmitted in React Express GET request

Hey everyone! I have successfully set up an endpoint on a local server for my React application. I created a GET endpoint to send data to the requester, but I am facing an issue where no data is being sent to any client requesting from this particular en ...

Steps to resolve the issue: The current experimental syntax 'classProperties' is not supported

I encountered an issue where the experimental syntax 'classProperties' is not supported when trying to run my react js application. My goal is to increment the value inside a <span> when a ` button is clicked. Below is the excerpt of my c ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

React UseEffect cleanup happening before Popstate event fires

After experimenting with different setups, I have managed to simplify my code to the bare minimum: import { useEffect } from "react"; const useUnsavedChangesAlert = () => { useEffect(() => { const handleRouteChange = (event) => { ...