[SOLVED] pc.Vec3 - lengthSq() and length()

Hi. Why is the lengthSq() method used in the update method instead of the length() method in this project? If you look at the logic, there is no difference for calculating the new position between the lengthSq() method and the length() method. I don’t understand why the lengthSq() method is needed. Does it work faster?

// update code called every frame
PointAndClick.prototype.update = function(dt) {
    if (this.direction.lengthSq() > 0) {
        // Move in the direction at a set speed
        var d = this.playerSpeed * dt;
        var newPosition = PointAndClick.newPosition;
       
        newPosition.copy(this.direction).scale(d);
        newPosition.add(this.playerEntity.getPosition());        
        this.playerEntity.setPosition(newPosition);     
        
        this.distanceToTravel -= d;
        
        // If we have reached our destination, clamp the position 
        // and reset the direction
        if (this.distanceToTravel <= 0) {
            this.playerEntity.setPosition(this.targetPosition);
            this.direction.set(0, 0, 0);
        }
    }
};

length() needs to use a square root to calculate the length of the vector which is ‘slow’. It probably doesn’t matter in this case where it’s only used once per frame but considered good practise not to use an expensive operation when you don’t need it.

@yaustar, do I understand correctly that if I need to find the value of the length of a vector, then it is better to use the length() method, but if I just need to determine if the value is not 0, then it is better to use the lengthSq() method, since it avoids the extra root extraction operation?

Yes, if you need to know the exact length then yes, you need to use length(). If you need to compare two vectors to see which one is longer/shorter, then you can compare their lengthSq to avoid two square roots.

2 Likes

@yaustar, thank you for the detailed explanation. :grinning: