☑ Explanation on some codelines from a tutorial

Hello all.

I’m running through the tutorials but struggle to understand parts of this one: http://developer.playcanvas.com/en/tutorials/animate-entities-with-curves/

this.startPosition = this.entity.getPosition().clone();

First of all, why clone the position by using the clone-command? If I assign a new variable which is set during initialization, shouldn’t it be sufficient to use this.entity.getPosition()?

Also, why would I want to set this.secsSinceAnimStart -= this.animationDurationSecs and not just set it to zero?

AnimatePosition.prototype.update = function(dt) {
    // Loop the animation forever by wrapping secsSinceAnimStart
    this.secsSinceAnimStart += dt;
    if (this.secsSinceAnimStart > this.animationDurationSecs) {
        this.secsSinceAnimStart -= this.animationDurationSecs; // Why not set this to zero?
    }
...
}

Why you have to clone object in JS:
http://blog.soulserv.net/understanding-object-cloning-in-javascript-part-i/

The getPosition function does not return a new pc.Vec3 instance. It returns an internal property. If getPosition is called again at some point, the returned vector will be updated. So if you store a reference to the returned vector, it may change at some future time. The way to avoid this is to create a new copy by calling clone.

As for the second question, yes, it looks like you could also just set the variable to zero. Same thing, in effect.

Say this.secsSinceAnimStart is 0, this.animationDurationSecs was 0.8, and dt was 1 (this is just for the example sake), by setting this.secsSinceAnimStart to 0, it effectively means that the duration of the animation has taken 1 second rather then 0.8 secs.

Whether that matters is application dependent. :slight_smile:

Hello mikefinch. Thank you for your reply - it makes sense to me now :slight_smile:

Thank you for your answer - much appreciated :slight_smile: