Skip to content Skip to sidebar Skip to footer

Javascript Function That Works Like Actionscript's Normalize(1)

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) //

Solution 1:

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

functionnormalize(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;
  }
}

Solution 2:

This is how it could be written in Actionscript:

functionnormalize(p:Point,len:Number):Point {
    if((p.x == 0 && p.y == 0) || len == 0) {
        returnnewPoint(0,0);
    } 
    varangle:Number = Math.atan2(p.y,p.x);
    varnx:Number = Math.cos(angle) * len;
    varny:Number = Math.sin(angle) * len;
    returnnewPoint(nx,ny);
}

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

functionnormalize(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};
} 

Solution 3:

I also found this that seems to do it.

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

THANK YOU

Solution 4:

Port from the AS3 Point Class, parameter is the same as shown in the livedocs (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/Point.html#normalize() )

Point.prototype.normalize = function(thickness){
  var norm = Math.sqrt(this.x * this.x + this.y * this.y);
  this.x = this.x / norm * thickness;
  this.y = this.y / norm * thickness;
}

Post a Comment for "Javascript Function That Works Like Actionscript's Normalize(1)"