Watch camera position and rotation changes

I’ve integrated Babylon.js into a Vue 3 application. I want to get the current camera position and rotation whenever saving the current state. However, my watcher functions don’t work. If i try to get the position and rotation value before and after interacting with my 3D space, the values do not change. I there a way to watch position and rotation changes after initializing my camera?

  let camera = new ArcRotateCamera(
    null,
    Math.PI / 2,
    Math.PI / 2,
    3,
    new Vector3(0, 0, 0),
    scene
  );

  camera.attachControl()
  
  //watchers don't work
  watch(() => camera.position, (pos, prevpos) => {
    console.log(pos, prevpos);
  })

  watch(() => camera.absoluteRotation, (rotation) => {
    console.log(rotation);
  })

Solution clarification: It was pointed out that I need a reactive wrapper for my camera object. The code above is a simplification of what I’m actually working with, and reactive wrappers could not be used in my case. I did however end up creating a reactive object in my store to transfer camera data across components.

Is Camera | Babylon.js Documentation useful for you?

Your code should work for Free camera.
Example - Babylon.js Playground
For ArcRotate camera use camera.alpha and camera.beta - Babylon.js Playground

I don’t know Vue and so not watch neither. But camera.position won’t generally change, it’s camera.position.x/y/z that will change.

So maybe you need to watch for camera.position.x/y/z changes instead?

2 Likes

hey there ,

firslty i have to ask if you are only wanting the values at the moment of saving , why do you even want the overhead of making them reactive?

secondly you are just creating a variable and not using ref or reactive , which is how to set up variables that require vue’s reactive management.

Between ref and reactive you are going to need reactive because it handles nested property tracking.

you should look at the vue documentation to understand how to use these.

Certain structures within vue create variables in this manner without you knowing it , like those in the pinia state.

this info is important because you actually DO NOT want vue to make all of babylon reactive… it will tank performance.