Question about setting variable to entity.getPosition()

Without further context, shouldn’t these code snippets result in the exact same behavior?

let initPos = new pc.Vec3();
let test = this.object.getPosition();

initPos.x = test.x;
initPos.y = test.y;
initPos.z = test.z;
let initPos = this.object.getPosition();

If there is a discrepancy between these two snippets then I am probably unaware about how PlayCanvas handles variables here, but I would expect both of these to store the object’s current position in a variable which stays unaltered, even when the object’s position updates.

If I’m wrong disregard the following, otherwise this project might be interesting because I get different results depending on which of the snippets I use:
https://playcanvas.com/editor/scene/1634016

(Script moveCommand.cs, launch the project and press Play, observe the white cube - initPos will return a different value when using the latter piece of code, causing the cube to jump in position)

Not exactly, no.

getPosition returns a reference to an internal vec3 object, not a copy.

So

let initPos = new pc.Vec3();
let test = this.object.getPosition();

initPos.x = test.x;
initPos.y = test.y;
initPos.z = test.z;

Is creating a new vec3 object and copying the values across and is equivalent to

let initPos = this.object.getPosition().clone()

Whereas

let initPos = this.object.getPosition();

Is getting a reference to the internal vec3 object, not a copy.

Huh, that’s interesting. I assumed what I got was always a copy, since according to my tests the Vec3 object does not update when I call entity.setPosition.

That’s good to know, thanks.

It returns a global ‘temp’ vec3 object to save on garbage collection/memory allocations. It only changes when getPosition is called on any Entity.

Unlike C#, JS can’t allocate objects on the stack.