Move your mouse over the word to see the effect.
Without Vectors
var locX = 0, locY = 0;
var loc2X = 100;
var loc2Y = 50;
var dx = loc2X – locX;
var dy = loc2Y – locY;
var dist = Math.sqrt( (dx * dx) + (dy * dy) );
Utilizing Vectors
var loc:Vector3D = new Vector3D();
var loc2:Vector3D = new Vector3D(100, 50);
var dist2 = (loc2.subtract( loc )).length;
// or //
var dist3 = Vector3D.distance( loc, loc2 );
Both of the approaches yield the same result. But you can see that the vector approach will be far easier to manage when more variables and more complex operations are involved. A quick example of adding some values together.
var xLoc = 30;
var yLoc = 15;
var zLoc = 20;
var xLoc2 = 2;
var yLoc2 = 12;
var zLoc2 = 0;
// add the values together //
xLoc += xLoc2;
yLoc += yLoc2;
zLoc += zLoc2;
Vector Solution
var loc:Vector3D = new Vector3D(30, 15, 20);
var loc2:Vector3D = new Vector3D(2, 12, 0);
loc = loc.add( loc2 );
As you can see, much easier to read and follow, a great resource for getting started with vectors is Daniel Shiffman’s Nature of Code Series. The examples are done with Processing, eventually resulting in this book.
One Comment
Hi,
Thanks for this code.I am currently learning about the vector 3d and this code is great for utilisation.Thanks for this post.