0
\$\begingroup\$

I'm writing a Java formula based on this tutorial: 2-D elastic collisions without Trigonometry. I am in the section "Elastic Collisions in 2 Dimensions". Part of step 1 says:

Next, find the unit vector of n, which we will call un. This is done by dividing by the magnitude of n.

My below code represents the normal vector of 2 objects (I'm using a simple array to represent the normal vector).

int[] normal = new int[2];
normal[0] = ball2.x - ball1.x;
normal[1] = ball2.y - ball1.y;

I am unsure what the tutorial means by dividing the magnitude of n to get the un.

What is un? How can I calculate it with my Java array?

\$\endgroup\$
1
\$\begingroup\$

First off, using arrays is not the best way to represent Vector information in Java. Second, use floats. Take a look at LibGDX Vector2 class.

The magnitude of a vector is it's length, obtainable with the Pythagorean theorem:

a² = b² + c²

in your case, you can obtain it by:

float[] normal = new float[2];
normal[0] = ball2.x - ball1.x;
normal[1] = ball2.y - ball1.y;
float magnitude = (float)Math.Sqrt(normal[0]*normal[0] + normal[1] * normal[1]);
float[] un = new float[2];
un[0] = normal[0] / magnitude;
un[1] = normal[1] / magnitude;

let me reassure you that using Arrays is NOT good. With a properly Vector class it should be like:

Vector2 normal = new Vector2();
normal.set(ball2);
normal.sub(ball1);
Vector2 un = new Vector2();
un.set(normal);
un.normalize();

If you were going to a language where Operator overloading is possible:

Vector2 normal = ball2 - ball1;
Vector2 un = normal / normal.length();
\$\endgroup\$
  • \$\begingroup\$ Thanks very much for the help! I will try to implement this and let you know if it works out. Currently I am not using LibGDX library so I cannot use Vector2, Thanks! \$\endgroup\$ – Shijima Jun 4 '14 at 2:58
  • \$\begingroup\$ I took your advice and started to work with Vector2, while I am not using LIBGDX, I did copy over the Vector2 class and am using that for calculations. Definetly a better approach to arrays. Cheers! \$\endgroup\$ – Shijima Jun 9 '14 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.