[SOLVED] Storing local position in initialize

Hello, I was curious about the behaviour of a recent piece of code that I encountered. On initialize, I wanted to store the starting position of the entity, so that after it has moved around a bunch, I can “reset” it to the original starting position.

So the relevant code looked like this:

// initialize code called once per entity
DragObj.prototype.initialize = function() {

    this.dragging = false;
    this.startPos = this.entity.getLocalPosition();
};

DragObj.prototype.reset = function() {

    this.dragging = false;
    this.entity.setLocalPosition(this.startPos.x,this.startPos.y,this.startPos.z);
};

However, it would never move back when reset. When I debugged “this.startPos” I was finding that it was always being set to the last position of the entity and not the original value that it was set to. It was as if using this.startPos would call getLocalPosition again and not just on initialize.

Is that expected behavior?

Thanks!

getLocalPosition returns a reference to pc.Vec3 that is changed internally by the Entity rather than a copy. JS doesn’t have a return by value option for object unless we create a new object in getLocalPosition but that risks creating more garbage.

As you need to a keep the value of the initial position of the Entity, clone the position. ie:

// initialize code called once per entity
DragObj.prototype.initialize = function() {

    this.dragging = false;
    this.startPos = this.entity.getLocalPosition().clone();
};

DragObj.prototype.reset = function() {

    this.dragging = false;
    this.entity.setLocalPosition(this.startPos);
};

Understood, thanks for the info!