Changing Material Properties at Runtime

You can change any material properties you find in the editor at runtime as well. This might be switching the texture for a flipbook, highlighting an object to indicate interactivity or to simply animate the specularity based on weather.

In Wonderland Engine, you can retrieve a material used by a mesh component by retrieving the component with Object3D.getComponent or specify a parameter to your custom component with type Property.material().

Change material properties 

Changing material properties is as simple as setting the corresponding properties on a Material.

1material.diffuseColor = [1, 1, 0, 1]; /* R, G, B, A */
2material.specularity = 2;
3material.diffuseTexture = someTexture;

Any property that can be set from the material properties panel, can be set here.

Example: Fade component 

The example below animates the alpha value of the material based on time. This could be used as a fade in effect for an object.

Note that every object that uses the material set on the mesh component will be affected by the animation. To make the animation unique to the object, the component uses Material.clone to retrieve a unique instance and set that to the mesh.

 1import {Component, Property} from '@wonderlandengine/api';
 2
 3export class FadeIn extends Component {
 4  static TypeName = 'fade-in';
 5  static Properties = {
 6    /* Fade duration in seconds */
 7    duration: Property.float(2.0),
 8    /* Starting alpha value */
 9    startAlpha: Property.float(2.0),
10    /* Final alpha value */
11    endAlpha: Property.float(2.0),
12  };
13
14  start() {
15    /* Retrieve material from mesh component attached to this object */
16    const mesh = this.object.getComponent('mesh');
17    if(!mesh) throw new Error('Missing mesh component on the object.');
18    /* Ensure we don't accidentally change other objects using the same
19     * material */
20    this.material = mesh.material.clone();
21    mesh.material = this.material;
22  }
23
24  onActivate() {
25    this.alpha = 1.0;
26    this.time = 0;
27  }
28
29  update(dt) {
30    this.time += dt;
31
32    this.alpha = startAlpha + (endAlpha - startAlpha)*Math.min(1.0, this.time/this.duration);
33    /* No need to call update() after endAlpha is reached */
34    if(this.alpha == this.endAlpha) this.active = false;
35
36    /* Set the alpha of the diffuse color. For other materials, you may need to modify
37     * a different property */
38    const c = this.material.diffuseColor;
39    this.material.diffuseColor = [c[0], c[1], c[2], this.alpha];
40  }
41}

Note that the material properties, like diffuseColor here, depend on the pipeline and shader used. You may want to modify flatColor for “Flat Opaque” instead, for example, or something completely different for custom shaders.

Any property shown in the material properties panel for the material can be edited in this way.