Friday, March 28, 2008

How to calculate the closest distant object


I am not a huge math geek, but I do like to come up with solutions. I feel as though I am moving closer to the programming world and less on the Graphic Design realm. Which is fine by me, I can focus my creativity to illustrations and paintings on my spare time. Understand, that I am no means a programmer at his pureness. I am learning every step of the way.

What I do like about blogging, is the journal entry aspect. This is where I can write things up that I have discovered. I am most happy to share what I learn with anyone else who chooses to have interest.

Now, with that disclaimer out there. If I had a focused object and many other objects surrounding that focused object; How could I find the closest object to that focused object? So I was proposed this question a couple of weeks ago.

I immediately thought of the Pathagreom Theorem (a(Square) + b(square) = c(square)). I said to my self, I understand of the problem. If I were to get the distance of all the objects x and y positions and subject them by the x and y position of the focused object, I could get the distances of each one to the focus object. I could than get the distance between an object and a main object by simply using ActionScripts Math.sqrt() function by passing in the distances x and y positions.

Okay, so if I am able to get the distances between each object and the focused object; I would than have to store the coordinates some where for checking, later. I stored each result distance into an array. After I stored all my distances, I then sorted the array valued numbers in numeric order by using the sort() function built-in ActionScript. If I were to trace out the distances array on it’s first array, I would get the closest number to the main object. This is really cool and all, but how can I really utilize this, one would say.


var distances:Array = [];
var objRef:Array = [];

for ( var i:int = 0; i < number =" this[" number =" this[" number =" Math.round(Math.sqrt(">


I looked further into this, and asked myself a question. How can I find the nearest object to the main object. So added a few more lines of code. I first added a new array, this is so I can keep track of my distance and object references. Than in my original for loop I stored my objects references into the new array. Each object reference is placed into a datatype Object. This is all done for reference checking later.

Now, after I have my numeric values sorted in order; I now create another for loop. This simple loop will go through each object reference and check if the closest distance matches the object referenced distance. If this is correct, we can now do what ever we please with that object.


var distances:Array = [];
var objRef:Array = [];
var num:int = 3;

for ( var i:int = 0; i < number =" this[" number =" this[" number =" Math.round(Math.sqrt(" int =" 0;">

No comments: