Reputation: 165
I think my current problem is related to intercept theorems that everybody learned at school, but that was quite some time ago and I am kind of getting stuck halfway.
I have two Vectors in a 2 dimensional space called v1
and v2
.
What I want to know are the coordinates of a vector v3
which is on the line segement between v1
and v2
.
What I know about v3 is the length of the line segement between v1
and v3
and v2
and v3
.
I my thoughs are always circling about the using the slope between v1
and v2
to determine the coordinates of v3
but at this point I'm getting stuck.
This the actual code I used for the issue:
private Vector2 getPointOnLine(Vector2 v1, Vector2 v2, float distance) throws Exception
{
double lengthOfSegment=Math.floor(Math.pow(v2.x - v1.x, 2)+Math.pow(v2.y-v1.y,2));
Vector2 slopeXY=v2.sub(v1);
float slope=1/slopeXY.x;
slopeXY.x=slopeXY.x*slope;
slopeXY.y=slopeXY.y*slope;
}
The actuell problem is game related, I want to let an allied unit (v2) follow the player(v1), but always keep a specific distance (distance).
I'm using LibGDX, are there by chance any library functions that can do this work for me?
Upvotes: 2
Views: 1178
Reputation: 4100
All you need is the ratio of the distances d(v1,v3)
and d(v1,v2) = d(v1,v3) + d(v3,v2)
. Let
r = d(v1,v3)/(d(v1,v3) + d(v3,v2))
Then
v3 = v1 + r(v2-v1)
is the answer to your question.
Proof: If d(v1,v3)=0
, r=0
and v3=v1
. If d(v3,v2)=0
then r=1
and v3 = v1+v2-v1 = v2
. The formula for v3
is linear, and it passes through both v1
and v2
, so v3
is always on the line between those vectors. Finally, norm(v3-v1) = r * norm(v2-v1) = d(v1,v3)
and a similar calculation for norm(v2-v3)
.
Upvotes: 0
Reputation: 689
I think you are trying to interpolate and get a vector which is a 'mix' of v1 and v2. This will be on the line between them. (Assuming v1 and v2 are treated as position vectors) You can do this by taking a weighted average of the vectors, but if the distance is given in absolute terms rather than relative, then you will need to convert:
Actually, it turns out libGDX vectors can do this for you!:
private Vector2 getPointOnLine(Vector2 v1, Vector2 v2, float distance)
{
double length = Math.hypot(v1.x - v2.x, v1.y - v2.y);
distance /= length;
return v1.cpy().lerp(v2, distance);
}
Vector2.lerp is a linear interpolation method provided by libGDX
Upvotes: 1