How to calculate cross product with source

Posted on November 11, 2007

Here’s a bit of source code to calculate the cross product of 3 vectors.

If you have no idea what a cross product is, imagine folding a piece of paper into a triangle. You then take a pencil and stick it through the center. Where ever the pencil is pointing, that’s what the cross product is, or “surface normal”.

The vectors are the 3 corners of the piece of paper.

public function cross(
x1:Number,y1:Number,z1:Number,
x2:Number,y2:Number,z2:Number,
x3:Number,y3:Number,z3:Number):void{
var px1:Number = (x2-x1)*1024;
var py1:Number = (y2-y1)*1024;
var pz1:Number = (z2-z1)*1024;

var px2:Number = (x3-x1)*1024;
var py2:Number = (y3-y1)*1024;
var pz2:Number = (z3-z1)*1024;

var nx1:Number = ((py1 * pz2) – (pz1 * py2));
var ny1:Number = ((pz1 * px2) – (px1 * pz2));
var nz1:Number = ((px1 * py2) – (py1 * px2));

var length:Number = Math.sqrt(nx1*nx1+ny1*ny1+nz1*nz1);
nx = nx1 / length;
ny = ny1 / length;
nz = nz1 / length;
}

I multiply the px, py, pz numbers by 1024 for better precision. The “returned” values, nx, ny, nz are the coordinates of the normal or “cross product”, it will range from -1 to 1. If you want them to be of length, just multiply by anything greater than 1.

include(“test.php”);ebayrss(“picross”);

Categories: Uncategorized


Leave a Reply