javascriptthree.jsdegreesdat.guiradians

Three.js How to convert values to degrees in the control panel using dat.GUI?


I made a simple slider in control panel to modify the position and rotation of an object. I have no problem with the position, as the values are relative, but I'd like to show the rotation's values in degrees. Here is what I have in the rotation controls:

gui
  .add(mesh.rotation, "x")
  .min(Math.PI * -1)
  .max(Math.PI)
  .step(0.01)
  .name("Rotar en X");

And this is how it is shown in the control panel:

COntrol panel of dat.GUI

The idea is to show -180 and 180


Solution

  • You're going to have to create a placeholder object that holds the values in degrees, then use the .onChange() event to know when the value changes. That's when you can convert the degrees into radians to assign to your mesh rotation.

    // Placeholder holds values in degrees
    var degrees = {
        x: 0,
        y: 0,
        z: 0
    };
    
    gui
        .add(degrees, "x")
        .min(-180)
        .max(180)
        .step(1)
        // This function is called each time the value is changed
        .onChange(() => {
            console.log(degrees.x);
    
            // Convert the degrees to radians, then assign to mesh rotation
            mesh.rotation.x = THREE.MathUtils.degToRad(degrees.x);
        });
    

    I'm using THREE.MathUtils.degToRad() to convert from degrees to radians.