类似actionscript的Javascript函数';s正常化(1)
我需要一个公式来返回xy点的规格化数字-类似于actionscript的normalize()函数类似actionscript的Javascript函数';s正常化(1),javascript,actionscript-3,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 这是如何在Actionscript中编写的: function normalize(p:Point,len:Number):Point { if((p
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
这是如何在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};
}
我认为as3函数只是一种缩放单位向量的方法:
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;
}
}
我还发现这个似乎可以做到这一点
var len = Math.sqrt(normal.x * normal.x + normal.y * normal.y)
normal.x /= len;
normal.y /= len;
谢谢您来自AS3 Point类的端口,参数与livedocs()中显示的参数相同
精确副本;)
规范化
在Actionscript中做什么?是这样吗:我没有考虑过0,0分的情况。抢手货不过,在这种情况下,您可能希望将该点设置为0,0(目前,您将保留传递该点的状态)。此外,我意识到如果比例为零,也不需要计算任何东西。@Juan是的,我保留了点,因为要得到零长度,x和y都必须为0,所以点已经是(0,0)。我没有优化上述版本;)“缩放”是将点标准化的单位吗?例如,比例为1时,x和y值的范围为-1到1?此外,该链接不再工作。
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;
}