The noise function creates a consistent scale for cubes that were originally random

My challenge involves smoothly scaling cubes with random initial scaling. However, I'm encountering an issue where the cubes scale almost identically after a short period of time, even though I'm utilizing a random noise function for scaling. Can you help me identify the problem in my code?


Take a look at the preview here and the live snippet here

You will notice that the cubes' scaling becomes nearly identical very quickly.


Below is the code snippet:

    const random = require("canvas-sketch-util/random");
    const palettes = require("nice-color-palettes");

    random.setSeed(19);

    const palette = random.pick(palettes);

    // Ensure ThreeJS is in global scope for the 'examples/'
    global.THREE = require("three");

    // Include any additional ThreeJS examples below
    require("three/examples/js/controls/OrbitControls");

    const canvasSketch = require("canvas-sketch");

    const settings = {
      // Make the loop animated
      animate: true,
      // duration: 5,
      fps: 30,
      playbackRate: "throttle",
      // Get a WebGL canvas rather than 2D
      context: "webgl",
      attributes: {
        antialias: true
      }
    };

    const sketch = ({ context }) => {
      //#region Scene setup
      // Create a renderer
      const renderer = new THREE.WebGLRenderer({
        canvas: context.canvas
      });

      renderer.setClearColor("aquamarine", 1);

      const camera = new THREE.OrthographicCamera();
      const controls = new THREE.OrbitControls(camera, context.canvas);
      const scene = new THREE.Scene();

      scene.add(new THREE.AmbientLight(0x404040));

      const light = new THREE.PointLight(0xffffff, 5, 15);
      light.position.set(-1, 2, 4).multiplyScalar(1.5);
      scene.add(light);

      const light2 = new THREE.PointLight(0xffffff, 1.5, 15);
      light2.position.set(3, 0, 2).multiplyScalar(1.5);
      scene.add(light2);

      const geometry = new THREE.BoxGeometry(1, 1, 1);

      const getNoise = (x, time) => {
        return random.noise2D(x, time, 0.5) * 0.5 + 0.5;
      };

      for (let index = 0; index < 2; index++) {
        const mesh = new THREE.Mesh(
          geometry,
          new THREE.MeshStandardMaterial({
            color: random.pick(palette),
            flatShading: true,
            roughness: 0.75
          })
        );
        mesh.name = `mesh-${index}`;
        mesh.position.set(
          random.range(-1, 1),
          random.range(-1, 1),
          random.range(-1, 1)
        );
        mesh.scale.set(
          random.range(0.04, 0.5),
          random.range(0.04, 0.5),
          random.range(0.04, 0.5)
        );
        scene.add(mesh);
      }
      //#endregion

      // draw each frame
      return {
        // Handle resize events here
        resize({ pixelRatio, viewportWidth, viewportHeight }) {
          renderer.setPixelRatio(pixelRatio);
          renderer.setSize(viewportWidth, viewportHeight, false);

          const aspect = viewportWidth / viewportHeight;

          // Ortho zoom
          const zoom = 1.5;

          // Bounds
          camera.left = -zoom * aspect;
          camera.right = zoom * aspect;
          camera.top = zoom;
          camera.bottom = -zoom;

          // Near/Far
          camera.near = -100;
          camera.far = 100;

          // Set position & look at world center
          camera.position.set(zoom, zoom, zoom);
          camera.lookAt(new THREE.Vector3());

          // Update the camera
          camera.updateProjectionMatrix();
        },
        // Update & render your scene here
        render({ time, playhead }) {
          scene.children.forEach(obj => {
            if (obj.isMesh !== true) {
              return;
            }
            // console.log(`${obj.name}: `,getNoise(obj.scale.z, time));
            // console.log(scene);
            obj.scale.set(
              // obj.scale.x,
              // obj.scale.y,
              // obj.scale.z,
              getNoise(obj.scale.x, time),
              getNoise(obj.scale.y, time),
              getNoise(obj.scale.z, time)
            );
          });

          controls.update();
          renderer.render(scene, camera);
        },
        // Dispose of events & renderer for cleaner hot-reloading
        unload() {
          controls.dispose();
          renderer.dispose();
        }
      };
    };

    canvasSketch(sketch, settings);

Answer №1

When trying to calculate the maximum value, there was significant noise difference causing flickering in the box.

Consider adjusting these parameters

return random.noise2D(x, time, 0.8) * 0.2 + 0.5;
OR
return random.noise2D(x, time, 0.7) * 0.3 + 0.5;
OR
return random.noise2D(x, time, 0.6) * 0.4 + 0.5;

Choose based on your desired frequency.

If this meets your requirements, you can find more information here https://stackblitz.com/edit/react-hhurr3?file=index.js

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

Update a specific division

Looking for suggestions on how to automatically refresh a div? I'm currently developing a chess game and I need the div to reload every time one player updates data in the database. The game is almost complete, but there's an issue where Player ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Quick way to access dropdown menu in Visual Code while selecting JavaScript/React code

While working on React code in Visual Studio Code, I accidentally triggered a dropdown menu when trying to copy and paste a section of my code. One of the items that caught my eye was labeled "Destructure JavaScript," which seemed intriguing. Unfortunately ...

I have no interest in using vanilla JavaScript to search for data in the database

I have a class assignment that requires the use of XMLHTTPREQUEST and JSON without using Jquery. The task involves searching for specific data through custom inputs. However, when I perform the search, I encounter this error which I'm unsure how to r ...

What is the solution to resolving the problem indicated by the error message "at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"?

I encountered an issue while attempting to send a token to the user for password reset. The error message I received is as follows: Error: there was an error sending the email, try again later at exports.forgotPassword (C:\\Users\\Abdur ...

Error encountered: React element type is not valid

I've been following a tutorial on building a WhatsApp clone using the latest versions of React and react-router-dom. However, when I try to start a new conversation, the component should render but instead it doesn't display anything. The proble ...

Having difficulty deciphering JWE Token using Python jwcrypt and NodeJS jose interaction

I am facing an issue with decrypting a JWE Token that was created using the jwcrypt library in Python and trying to decrypt it using the jose library in JavaScript. I have set up the A256KW and A256CBC-HS512 algorithms on both libraries and also provided ...

Discovering techniques to minimize the need for prop drilling in ReactJS component trees

As I was reading through the ReactJS documentation, I stumbled upon the section about Contexts where I found the following information: The page mentioned that if you only need to avoid passing certain props through multiple levels, using component compo ...

Adding content to an empty element will not produce the desired result

I'm trying to show each character of a string, which is stored in an array, one at a time. However, when I use threadsleep(a) with the code found here: http://jsfiddle.net/thefiddler99/re3qpuoo/, all the characters are displayed at once. There seems t ...

Sprockets could not locate the file for jquery.atwho

I have been attempting to integrate the jquery-atwho-rails into my application, a Rails gem designed for at.js. I have followed all the steps provided, executed bundle install, included the necessary code in both application.js and application.css, stopped ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

Changing the name of a JSON object in a Node.js environment

Is there a way to change the name of an object from "Cars" to "automobiles"? I attempted to use ObjectRenameKeys, but it only seems to work on the properties within objects and not the objects' names themselves. Initial Structure: "Cars": [ ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

Vue.js powered search bar for exploring countries worldwide (utilizing the restcountries API)

Despite successfully loading the API country data (as evidenced by the console.log() entry and the accompanying picture of my work desk), the country information does not display when hovering the mouse cursor over the search bar field (expecting a dropdow ...

Basic jQuery selector fails to function in Chrome browser

Looking for some help with a script on my website (): $('#scheduleBox .selectCity select option').click(function() { var cityToShow = $(this).attr('value'); switch(cityToShow) { case '0': ...

Having trouble getting Uploadify to work as a jQuery Plugin?

The jQuery plugin Uploadify has been implemented on my website, but I am facing issues with the file uploads. The file input is being replaced correctly by Uploadify markup, including the Flash button, however, when selecting multiple files, nothing happen ...

Is it feasible to alter the value by selecting an option from a dropdown menu using Python and Selenium?

Using python selenium for searches on a specific website, I encountered an issue with selecting sections through a dropdown menu. The site's search dialogue offers the choice of searching all sections or a particular section. To pick a section, a sepa ...

How is it that when I rotate my figure around the x and y axes, its shape transforms as depicted in the image below?

Whenever I adjust the position along the x or y axis, my shape changes as shown in the image below. How can I correct this issue? I am working with Three.js. const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth ...

What steps do I need to take to incorporate Material UI icons into my REACT project?

After reviewing the documentation, I found it somewhat confusing with terms such as "MaterialIcon, SVGIcons, Icons". If you are interested, you can check out the link here. I am looking for a simple explanation of the process from installation to using th ...

Selenium-webdriver is having trouble locating an element through the CSS selector

I encountered an issue while using selenium-webdriver in JavaScript to input a value into a field. Here is my test.js code: async () => { let driver = await new webdriver.Builder().forBrowser("chrome").build(); try { await driver.get("http://te ...