Please note that ExpatTech is close for the Christmas and New Year holidays. We will re-open on 2nd January 2024.

ExpatTech Techblog

Peter Todd 2010.01.29. 14:21

Flash Cookbook - Geometry - Fine tuning Point class Part 2. Length.

Okay. Here we are with the second question. Can we fasten the request for length? - asked the little grasshopper.

Yes, we can. The result is a 15% speedup.

override public function get length():Number
{
     return Math.sqrt(x * x + y * y);
}

We have to mark the getter for override. That is all. By the way, try not to use the built-in Math.pow() for powering if you know the exponent.

"Dear Master,

Why is length a read-only property? I wanna set the length. Please make it possible for me.

Thank you for you time

The Little Grasshopper"

We got this letter earlier and wan't to respond to it. We don't want to have suffering flash coders around our household.

And for your information here is the trick:

public function set length(length:Number):void
{
     var angle:Number = x >= 0 ? Math.atan(y / x) : Math.atan(y / x) - Math.PI;

     if(x == 0 && y == 0) angle = 0;

     x = Math.cos(angle) * length;
     y = Math.sin(angle) * length;
}

First we get the angle of the point:

var angle:Number = x >= 0 ? Math.atan(y / x) : Math.atan(y / x) - Math.PI;

and keeping this angle we set the new coordinates:

x = Math.cos(angle) * length;
y = Math.sin(angle) * length;

for more information see the definition of sine and cosine.

Isn't this awesome? We expanded the Point class!

Of course, as it is written in Little Grasshopper's second letter (1), requesting the length is a dynamic metho, meaning that it calculates the length instead of using a constant.

But. Since we don't want to make a setter for the coordinates (optimizing issues - just think about it), we can't catch the moment of chaning such a value. Therefore we can't use a constant for the lenght (what otherwise could be an optimising step).

It has to be considered when to use it.