Modifying shapes and figures in three-dimensional Javascript

I am currently struggling to transform a cube into a sphere in Three.js either after a specific time interval or upon an event click. I have attempted changing the geometry property from BoxGeometry to SphereGeometry with no success. Despite trying some potential solutions I found, I've reached a roadblock.

Here is my initial setup:

export class ThreeJSService {
  geometry: THREE.BoxGeometry;
  camera: THREE.PerspectiveCamera;
  cube: THREE.Mesh;
  movingObject;
  renderer: THREE.WebGLRenderer;
  scene: THREE.Scene;
  texture: THREE.Texture;
  /**
   * Setups scene for 3d objects
   */
  constructor() {
    this.scene = new THREE.Scene();
    this.texture = new THREE.TextureLoader().load('assets/apartment_background.png');
    this.scene.background = this.texture;

    this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    this.renderer = new THREE.WebGLRenderer();

    this.geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
    const material = new THREE.MeshBasicMaterial({ color: 0x348713 });
    //Creating cube object using box geometry and setting material
    this.cube = new THREE.Mesh(this.geometry, material);

    // Creating movingObject with cube as object, initial direction values
    this.movingObject = {
      object: this.cube,
      geometry: this.geometry,
      direction: {
        x: 0.03,
        y: 0,
      },
    };
  }

  /**
   * Sets up all required elements for the scene
   * @param {HTMLElement} parent The element to attach to
   */
  setup(parent: HTMLElement) {
    const canvas = this.renderer.domElement;
    this.scene.add(this.cube);

    this.camera.position.z = 5;
    parent.appendChild(canvas);
  }


  /**
   * Provides animation to the rendered object by rotating it and changing its direction at borders
   * @param {number | undefined} headerHeight The height of the header
   */
  animate() {
    const header = document.getElementById('header')?.clientHeight;
    this.renderer.setSize(window.innerWidth, window.innerHeight - (header ? header : 0));

    this.movingObject.object.rotateX(0.01);
    this.movingObject.object.rotateY(0.01);
    requestAnimationFrame(this.animate.bind(this));
    this.renderer.render(this.scene, this.camera);

    this.movingObject.object.position.x += this.movingObject.direction.x;

    // Check if the position of the cube is on the border
    if (this.cube.position.x > 7.3 || this.cube.position.x < -7.3) {
      this.movingObject.direction.x = -this.movingObject.direction.x;
    }
  }

Any assistance would be greatly appreciated!

Answer №1

Witness a fascinating demonstration where a 3D shape transforms after a brief pause.

let camera, scene, renderer;

initialize();
display();

function initialize() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.set(2, 2, 2);
  camera.lookAt(0, 0, 0);

  scene = new THREE.Scene();

  geometry = new THREE.BoxGeometry();
  material = new THREE.MeshNormalMaterial();

  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({antialias: true});
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  setTimeout(function() {

    mesh.geometry.dispose();
    mesh.geometry = new THREE.SphereGeometry();

    display();

  }, 2000);

}

function render() {

  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e09488928585a0d0ced1d4d1">[email protected]</a>/build/three.min.js"></script>

Answer №2

I successfully managed to make it function. Below is the solution I came up with:

 changeShape() {
    this.interval = (Math.floor(Math.random() * (400 + 1)) * 1000);
    
    if (this.switch) {
      setTimeout(() => {
        this.movingObject.object.geometry.dispose();
        this.movingObject.object.geometry = new THREE.CylinderGeometry(0.5, 0.5, 2);

        this.switch = false;
      }, this.interval);

    } else {
      setTimeout(() => {

        this.movingObject.object.geometry.dispose();
        this.movingObject.object.geometry = new THREE.SphereGeometry(0.5, 8, 8);
        this.switch = true;

      }, this.interval);
    }
  }

Your help was greatly appreciated!

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

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

Infuse the theme into the sx prop of MUI 5

The code snippet above was originally written using MUI v4: const useStyles = makeStyles(theme => ({ toolbarMargin: { ...theme.mixins.toolbar } })) To update this code to MUI v5 and utilize the sx prop, I attempted the following implementation: ...

What are effective solutions to reduce the increasing Next.js bundle size caused by dynamic component lookup?

tldr: For more information, please visit the repository. The common.js file includes all dependencies, even though only one is used on the current page. http://localhost:3000/components/ComponentOne http://localhost:3000/components/ComponentTwo Live dem ...

Determine the Button's State by Monitoring Changes in the TextBox Text

I have been tasked with developing a web application for my company. The main components of the application are a button and a textbox. My goal is to allow users to input a value into the textbox, which will then be processed when they click on the button ...

Angular2 does not load Js twice

I specified the path to my JS file in angular.cli. It loaded successfully during the initialization of the Angular app, but when navigating back to the component, it failed to load. Any suggestions on how to fix this issue would be greatly appreciated. Th ...

Collision events are not being triggered in ThreeJS and PhysiJS

I've encountered an issue with PhysiJS and Three JS where I am unable to handle collision events. Check out the code on Github : https://github.com/kevrmnd/soccer-physics (located in script.js file) The problem arises when I try to detect a collisio ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

Error: The data from the intermediate value cannot be parsed using the parseFromString() method and replaced with another value,

I'm working on a project where I need to display parsed HTML content within an element. However, before displaying it, I need to make some changes to the HTML using the `replace` method. But unfortunately, I encountered a TypeError: (intermediate valu ...

What is causing the Angular-UI TypeAhead code to display all items instead of filtered items?

I have been experimenting with the angular-ui typeahead directive to create a filtered input box that only shows items based on what has been typed. However, my current code is displaying all the items instead of just the filtered ones. If you'd like ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

The proper method for updating data on a backend API using Axios and Vue

I am working on a Vue application that includes several form fields. I want to ensure that any changes made by the user are saved in real-time to a backend database using a REST API with Axios, without requiring the user to click a save button. I have two ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Exploring variations in error handling for JavaScript promises in Node.js depending on whether the error is synchronous or asynchronous

Exploring the nuances of promise error handling for thrown errors and exceptions in the promise executor, particularly in comparison to reject, within a node.js context. Differences in handling between reject and throw/exceptions are evident. Some source ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

What impact does changing the Device Language have on a heading?

At the top of an html page, I have the word "Color" in a heading. If a user's device is set to British English, I would like the text to automatically switch to "Colour". What is the best way to accomplish this with minimal Javascript? ...

Refine the pandas Dataframe with a filter on a JavaScript-enabled website

I recently inherited a large software project using Python/Flask on the backend and HTML/Javascript on the frontend. I'm now looking to add some interactivity to one of the websites. I have successfully passed a dataframe to the webpage and can displa ...

What is the best way to overlay an SVG line on top of a CSS style?

Is there a way to make SVG lines appear on top of CSS-styled elements in my HTML file? I have a white background SVG created with JavaScript using d3, and I am adding CSS-styled rectangles on top of it. However, I also want SVG lines (created with JavaScri ...