Search code examples
javascriptcamerap5.js

How to return the camera position in p5js?


In P5js we can set the camera position with the command

camera([x], [y], [z], [centerX], [centerY], [centerZ], [upX], [upY], [upZ])

but how can I return the current camera position after some rotation going on with orbitControl() ? is there a function like cameraX to return the x coordinate of the current camera position like mouseX for the mouse?


Solution

  • You should be able to make a p5.Camera instance via createCamera(), hold to it and read/reuse properties such as x, y, z as needed.

    Here's the documentation example with a tweak:

    // Creates a camera object and animates it around a box.
    let camera;
    function setup() {
      createCanvas(100, 100, WEBGL);
      background(0);
      camera = createCamera();
      // optionally, call camera() on the instance with the same arguments as the global function
      //camera.camera([x], [y], [z], [centerX], [centerY], [centerZ], [upX], [upY], [upZ])
    }
    
    function draw() {
      background(255);
      if(!mouseIsPressed){
        camera.lookAt(0, 0, 0);
        camera.setPosition(sin(frameCount / 60) * 200, 0, 100);
      }
      box(20);
      // read cam params
      console.log(camera.eyeX + ',' + camera.eyeY + ',' + camera.eyeZ);
    }
    
    function mouseDragged(){
      orbitControl();
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>