Reputation: 49
I'm using three.js for doing animations. I want to dynamically update a material of a cube mesh. Here is example:
// create cube geometry
var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....];
var geometry = new THREE.CubeGeometry(50, 50, 50,0,0,0,material1 );
var cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
// ...
var material2 = [new THREE.MeshBasicMaterial({color:0xFFFFFF}), ...];
cube.geometry.materials = material2;
If I use CanvasRenderer, it works. But when I change to WebGL Renderer, it throws error: Uncaught TypeError: Cannot read property 'map' of undefined
How to update the material of a cube on runtime using WebGL?
Upvotes: 4
Views: 11887
Reputation: 404
I think the issue is that you're setting 'materials' and not 'material' on your cube.
cube.material = material2;
material.map = texture;
material.needsUpdate = true;
Upvotes: 2
Reputation: 104763
With a code fragment, it is difficult to know what is causing the error, but you cannot change materials that involve the presence or not of a texture. Try keeping all of your materials of the same type. Also, you may need to set material.needsUpdate
flag to true
.
You can find more detail and examples in the Three.js wiki about how to update things with WebGLRenderer
.
https://github.com/mrdoob/three.js/wiki/Updates
Also, here is a fiddle that does something similar to what you appear to be trying to do: http://jsfiddle.net/2FZU7/51/
EDIT: fiddle updated for three.js r.58
Upvotes: 4