Exploring the possibilities with three.js, I am working with two shapes: "squares" and a "sphere".
Each shape has an associated button. When the user clicks a button, the corresponding shape is added to the scene. However, there can only be one square and one sphere in the scene at a time.
The issue I'm facing is that when a new square is added, it should replace the existing one. Unfortunately, my current code doesn't seem to achieve this as the previous square remains when adding a new one.
Any suggestions or advice on how to solve this problem would be greatly appreciated. Thank you!
<html>
<head>
<title>My second three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<button id="button1">Square1</button>
<button id="button2">Square2</button>
<button id="button3">Sphere</button>
<script src="js/three.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
loader.load( 'square1.glb', function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button1").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( 'square2.glb', function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button2").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( 'sphere.glb', function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
sphere = node;
sphere.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button3").addEventListener("click", function(){
scene.add(sphere);
});
});
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>