I have two objects, A and B, each of them has a set of coordinates (x,y). How do I understand where is A in relation to B's position?

If I where to just check each coordinates I could do it like this:

B(x:5,y:5), A(x:4,y:5); x = 5-4 = 1; y = 5-5 = 0; A it's on the left

B(x:5,y:5), A(x:6,y:5); x = 5-6 = -1; y = 5-5 = 0; A it's on the right

B(x:5,y:5), A(x:5,y:6); x = 5-5 = 0; y = 5-6 = -1; A it's on top of B

B(x:5,y:5), A(x:6,y:5); x = 5-5 = 0; y = 5-4 = 1; A it's under B

But I was wondering, since I'm using a standard Vector2 data structure (from LibGDX), with the ability to normalize, compute distances, etc.. If I could do it using those methods instead of subtracting the coordinates each time.

If it can help, I need to know the position of A relative to B because A is supposed to push B, so if A it's on B's left, B needs to move right, etc...


If you want to get position A relative to B, you just need to substract them, like you were doing. If you want to make use of the methods, you can use the method "sub": https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Vector2.html#sub-com.badlogic.gdx.math.Vector2-

Vector2 relative = A.sub(B); //contains the position of A relative to B
Vector2 direction = B.sub(A); //direction that B will move after being hit by A
  • \$\begingroup\$ Yes, after waking up I got to the same conclusion! Thank you very much. :) \$\endgroup\$ – Paul May 9 '16 at 18:11

Coordinates of A xa,ya and B xb,yb and vector AB X=xa-xb ,Y=ya-yb

I give a formula to give point A in relation to point B in 8 directions.

For E=0,NE=1,N=2,NW=3,W=4,SW=5,S=6 and SE=7

F(X,Y)=MOD((4-2*(1+SIGN(X))* (1-SIGN(Y^2))-(2+SIGN(X))*SIGN(Y)



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.