1
\$\begingroup\$

I need to get coorinates of red point. Coordinates are just for example, it would be better to see the common formula. Found code like this, but it gains wrong result.()

Vector2 o = new Vector2(6f,2f);
Vector2 n = new Vector2(1f,4f);
Vector2 v = new Vector2(3f,2f);
Vector2 A = n.sub(o).nor();
float t = A.dot(v);
Vector2 result = A.scl(t);

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Looks like you're trying to project the point (3,2) on the line (1,4)-(6,2). You could take a look here or ask Google. \$\endgroup\$ – Vaillancourt Jan 17 '16 at 14:34
1
\$\begingroup\$

From you code I can't tell what the ownerv vector is so I can't tell you why it's giving you the wrong result.

But to do it from scratch, according to Wikipedia's article on vector projection, you can do the following;

  1. Create a vector a that is the direction from o to v.
  2. Create a vector b that is the direction from o to n.
  3. Let d be the dot product of a and b divided by the length of b (this will give you a scalar that is the distance from o in the direction of b).
  4. Create the result, target, by adding a vector of length d to o.

In code those steps could look like this;

Vector2 o = new Vector2(6f, 2f);
Vector2 n = new Vector2(1f, 4f);
Vector2 v = new Vector2(3f, 2f);

// The direction from o to v
Vector2 a = (new Vector2(v)).sub(o);

// The direction from o to n
Vector2 b = (new Vector2(n)).sub(o);

// d is the length along b where the project a will fall.
float d = (new Vector2(a)).dot(b) / b.len();

// Take the vector that is the normal of b, scale it by d and add it to the start point o, 
Vector2 target = (new Vector2(o)).add(b.nor().scl(d));

(Note that you probably don't want to new up as many Vector2s as I do in this example in your actual game code).

\$\endgroup\$

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.