Add or remove code in init function with datGUI

Hello colleagues, so I came up with a question to which I don’t seem to find an answer.

I have datGUI controls, and now I would like to make one, which would control the fog - simply enable or disable it.

My fog is just 4 lines in the init() function:

const fogcolor = 0xffffff;
const fognear = 10;
const fogfar = 100;
scene.fog = new THREE.Fog(fogcolor, fognear, fogfar);

Now I wonder, how could I tell datGUI, so when I un-tick or tick the fog option, it would add or remove those 4 code lines from the init() function? Or maybe there is another way to disable the fog?

My checkbox code looks like this:

let sb = gui.add( controlBoxParams, 'fog_on').name('Fog animation On/Off');
sb.listen();
sb.onChange( function ( value ) {
    if (value == true){
		//add fog code to init function
	}
    else {
		//remove fog from init function
	}
});

I just don’t quite know how I can tell the program to add or remove that code in specific function. Any ideas are welcome :beers:

My whole JS code can be seen here: https://pastebin.com/cgWTqrxF

When addding/removing fog, the materials require a recompilcation. This is actually explained in:

https://threejs.org/docs/index.html#manual/en/introduction/How-to-update-things

Here is a live demo that demonstrates this: https://jsfiddle.net/ndbL3t5o/1/

To avoid a recompilation of all materials, you can also use FogExp2 and just modulate the density.

2 Likes

I like the idea of FogExp2, I tried to implement it now, but it doesn’t quite work. How should I declare density parameter so that I could set it in the datGUI? My fog function looks like this:

const fogcolor = 0xffffff;
const density = 0.015;
scene.fog = new THREE.FogExp2(fogcolor, density);

Default value of fog_on is true, there is fog in the scene. However, if I turn it off, nothing changes:

let sb = gui.add( controlBoxParams, 'fog_on').name("Fog animation ON/OFF");
sb.listen();
sb.onChange( function ( value ) {
    if (value == true){
		density = 0.015;
		console.log("works");
		//add fog code to init function
	}
    else {
		density = 0;
		
		//remove fog from init function
	}
});

I think I’m doing something wrong with the variable density since it doesn’t pass the value as it should.

This will not affect fog if the init function is called before the change and not after.

Or set fog.near and fog.far to Infinity?

You would need to set fog.density.

2 Likes

Wonderful, did some tweaks according to your suggestion and it worked, final code looks like this:

let sb = gui.add( controlBoxParams, 'fog_on').name("Fog animation ON/OFF");
sb.listen();
sb.onChange( function ( value ) {
    if (value == true){
		scene.fog.density = 0.015;
	}
    else {
		scene.fog.density = 0;
	}
});

Everything works as expected, button reacts to on and off. Cheers :beers:

2 Likes