Any reliable polygon normal calculation code?
Posted
by
Jenko
on Game Development
See other posts from Game Development
or by Jenko
Published on 2011-02-03T15:29:08Z
Indexed on
2011/02/03
15:34 UTC
Read the original article
Hit count: 343
I'm currently calculating the normal vector of a polygon using this code, but for some faces here and there it calculates a wrong normal. I don't really know what's going on or where it fails but its not reliable.
Do you have any polygon normal calculation that's tested and found to be reliable?
// calculate normal of a polygon using all points
var n:int = points.length;
var x:Number = 0;
var y:Number = 0;
var z:Number = 0
// ensure all points above 0
var minx:Number = 0, miny:Number = 0, minz:Number = 0;
for (var p:int = 0, pl:int = points.length; p < pl; p++) {
var po:_Point3D = points[p] = points[p].clone();
if (po.x < minx) { minx = po.x; }
if (po.y < miny) { miny = po.y; }
if (po.z < minz) { minz = po.z; }
}
for (p = 0; p < pl; p++) {
po = points[p];
po.x -= minx;
po.y -= miny;
po.z -= minz;
}
var cur:int = 1, prev:int = 0, next:int = 2;
for (var i:int = 1; i <= n; i++) {
// using Newell method
x += points[cur].y * (points[next].z - points[prev].z);
y += points[cur].z * (points[next].x - points[prev].x);
z += points[cur].x * (points[next].y - points[prev].y);
cur = (cur+1) % n;
next = (next+1) % n;
prev = (prev+1) % n;
}
// length of the normal
var length:Number = Math.sqrt(x * x + y * y + z * z);
// turn large values into a unit vector
if (length != 0){
x = x / length;
y = y / length;
z = z / length;
}else {
throw new Error("Cannot calculate normal since triangle has an area of 0");
}
© Game Development or respective owner