[SOLVED] Value update issue

Hi,

I faced a problem with value update.

Sphere.prototype.initialize = function() {
    this.InitialPos = this.entity.getPosition(); 
}

Sphere.prototype.update = function() {
    console.log(this.InitialPos);
}

In the above code, I am trying to save the initial position of an entity in initialize. In another script I am moving the same entity.

In the above log the value of InitialPos variable is changing continuously which was actually assigned only once in the initialize function.
So I am rather confused on what mistake I am doing here.
Would be great if anybody could help me out.

Thanks.

Check out this post: Event is the only script communication method in script 2.0?

Thanks for the reply. I am getting the value of InitialPos in update. But the value is changing which is the actual problem I am facing.

try this ?

this.InitialPos.copy(this.entity.getPosition());

1 Like

Thank you fxcarl that worked.
even this worked

this.InitialPos = new pc.Vec3( this.entity.getPosition().x, this.entity.getPosition().y, this.entity.getPosition().z );

but why not

this.InitialPos = this.entity.getPosition();

is working?

I thought calling
this.entity.getPosition();
returns a reference, not value. We have to copy the value explicitly

But in API Reference thay mentioned that getPosition() returns value

getPosition()
Get the world space position for the specified GraphNode. The value returned by this function should be considered read-only. In order to set the world-space position of the graph node, use pc.GraphNode#setPosition.

var position = this.entity.getPosition();
position.x = 10;
this.entity.setPosition(position);

Returns
pc.Vec3 The world space position of the graph node.

Here is the link
API Reference

getPosition - does not creates new Vec3, it actually reuses existing one, that is why what it returns shall not be “taken” to other places.
So you do want copy or clone that vector.
Here is source of engine pointing to that: https://github.com/playcanvas/engine/blob/master/src/scene/graph-node.js#L654