Javascript函数就像actionscript的规范化一样(1)

时间:2010-08-28 18:59:30

标签: javascript actionscript-3

我需要一个公式来返回xy点的标准化数字 - 类似于actionscript的normalize()函数。

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

4 个答案:

答案 0 :(得分:5)

我认为as3 normalize函数只是一种扩展单位向量的方法:

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

答案 1 :(得分:2)

这是在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);
}

所以,我猜在JS中它可能是这样的:

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

答案 2 :(得分:1)

我也发现这似乎是这样做的。

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

谢谢你

答案 3 :(得分:0)

来自AS3 Point Class的端口,参数与在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;
}