Question

I am making a platformer game in C++ using SFML and Box2D libraries. The player has a pistol, I'm trying to implement shooting.

Box2D has a RayCast function, which needs two positions to check for intersections between. I have the player position and the mouse position. Currently the line checks between those two, not ideal.

I need a third position, which is the position, where the pistol shot would end. The distance between the player position and the third position should always be 1000.

Était-ce utile?

La solution

The maths are pretty simple. Consider the following line, A and B being your known points (A is the origin of the segment, ie. your player) and C being the third point you're looking for:

   A-----------B------------C
(Xa,Ya)     (Xb,Yb)      (Xc,Yc)

Now the distances:

AB = sqrt( (Xb - Xa)² + (Yb - Ya)² )
AC = 1000

Cross-multiply to get Xc:

AB -> Xb - Xa
AC -> Xc - Xa

Xc - Xa = AC * (Xb - Xa) / AB
Xc = Xa + (AC * (Xb - Xa) / AB)

Similarly, Yc = Ya + (AC * (Yb - Ya) / AB)

Note that this also works if C is between A and B, the only (obvious) restriction is if A and B are the same point (AB = 0, conveys no direction information and rightly yields a division by zero).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top