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