I've been experimenting with Threejs to learn more about it, and I encountered an issue sooner than expected. I'm not sure if the problem lies in my code or within the framework itself (though I suspect it's on my end).
The goal was to swap one object for another when a button is clicked. Currently, my test code loads a cube initially and attempts to replace it with a sphere upon clicking the button. However, instead of the desired outcome, I'm faced with the following error:
TypeError: geometry.addEventListener is not a function
geometry.addEventListener( 'dispose', onGeometryDispose );
This is the HTML content:
<!doctype html>
<html lang="en">
<head>
<title>My Test Page</title>
<meta charset="utf-8>
</head>
<body style="margin: 0;">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.js"></script>
<script src="OrbitControls.js"></script>
<script>
var WIDTH = 500,
HEIGHT = 500;
var scene = new THREE.Scene();
var aspect = WIDTH / HEIGHT;
var camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
camera.position.set(0,0,5);
scene.add(camera);
var renderer = new THREE.WebGLRenderer();
renderer.setSize( WIDTH , HEIGHT );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
controls = new THREE.OrbitControls(camera, renderer.domElement);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
animate();
</script>
<div>
<button onclick="updateObject();">Update Object</button>
</div>
</body>
<script src="scripts.js" type="text/javascript" charset="utf-8"></script>
</html>
Here's the function that should change the object:
function updateObject() {
scene.remove(cube)
var position = new THREE.Vector3(0, 0, 0);
var geometry = new THREE.SphereGeometry(1.4);
var material = new THREE.MeshNormalMaterial();
var sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
}
Could you help identify what I might be doing wrong?
For Orbit controls, visit: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/OrbitControls.js