简体   繁体   English

将线从2点延伸到一定长度

[英]Extending a line to a certain length from 2 points

I am making a platformer game in C++ using SFML and Box2D libraries. 我正在使用SFML和Box2D库在C ++中开发平台游戏。 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. Box2D具有RayCast函数,该函数需要两个位置来检查它们之间的交集。 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. 玩家位置与第三位置之间的距离应始终为1000。

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是您的已知点(A是该段的起点,即您的玩家),C是您要查找的第三点:

   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: 交叉乘以得到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) 同样, 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). 请注意,如果C在A和B之间,这也是可行的,唯一(明显)的限制是,如果A和B是同一点( AB = 0 ,不传递方向信息,并且正确地除以零)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM