views:

55

answers:

3

I need a formula that returns normalize numbers for xy point - similar to actionscript's normalize() function.

var normal = {x:pt1.x-pt2.x,y:pt1.y-pt2.y};

normal = Normalize(1) // this I do not know how to implement in Javascript
+2  A: 

This is how it could be written in Actionscript:

function normalize(p:Point,len:Number):Point {
    if((p.x == 0 && p.y == 0) || len == 0) {
        return new Point(0,0);
    } 
    var angle:Number = Math.atan2(p.y,p.x);
    var nx:Number = Math.cos(angle) * len;
    var ny:Number = Math.sin(angle) * len;
    return new Point(nx,ny);
}

So, I guess in JS it could be something like this:

function normalize(p,len) {
    if((p.x == 0 && p.y == 0) || len == 0) {
        return {x:0, y:0};
    }    
    var angle = Math.atan2(p.y,p.x);
    var nx = Math.cos(angle) * len;
    var ny = Math.sin(angle) * len;
    return {x:nx, y:ny};
} 
Juan Pablo Califano
+2  A: 

I think the as3 normalize function is just a way to scale a unit vector:

function normalize(point, scale) {
  var norm = Math.sqrt(point.x * point.x + point.y * point.y);
  if (norm != 0) { // as3 return 0,0 for a point of zero length
    point.x = scale * point.x / norm;
    point.y = scale * point.y / norm;
  }
}
Patrick
@Patrick. I had not considered the case of a 0,0 point. Good catch! You might want to set the point to 0,0 in that case, though (currently, you are leaving it as it was passed). Also, I realized that if scale is zero there's no need to calculate anything either.
Juan Pablo Califano
@Juan Yes i left the point as it, since to get a zero length both x and y have to be 0, so the point is already (0,0). I have not optimised the version above ;)
Patrick
A: 

I also found this that seems to do it.

var len = Math.sqrt(normal.x * normal.x + normal.y * normal.y)
normal.x /= len;
normal.y /= len;

THANK YOU

Yes that's my answer ;)
Patrick