user-interfacerandomthree.jsdat.gui

Randomising Value in Dat.GUI


I'm using dat.gui to control values but want to add a button to randomise the value. Is there a way to do this? I have the randomise button but I cannot figure out how to reference the parameter to change its value.

Basic code is something like:

const params = {}
params.num = 20

gui.add(params, 'num').onChange(doSomething)

//on clicking the 'Randomise' button I would essentially like this to happen:

gui.(params, 'num').setValue( randomValue ).onChange(doSomething)

Is there some way I can reference the parameter, and then set its value to x? Thanks in advance!


Solution

  • You can change the value of a property and use .listen() in GUI to listen for changes of the property.

    Click randomize on GUI and see what it does:

    <script type="module">
    import {GUI} from "https://cdn.jsdelivr.net/npm/three@0.125.2/examples/jsm/libs/dat.gui.module.js";
    
    let params = {
      value: 20,
      randomize: _ => {
        params.value = Math.random() * 40;
      }
    }
    
    let gui = new GUI();
    gui.add(params, "value", 0, 40).step(0.1).listen();
    gui.add(params, "randomize");
    
    </script>