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!