查找两个在平面上移动的球之间是否发生碰撞 Python

huangapple go评论69阅读模式
英文:

Find if there is collision between two balls moving in a plane python

问题

以下是翻译好的部分:

我有以下的球配置:

P=(115,100)
T=(253,211)
C=(389,464)
r=60

球的中心在C点,半径为r,它会沿着一条直线从C点运动到P点。

在这个轨迹上可能会有一个半径为r的球T,它会与球C发生碰撞并使球C偏离它的轨迹。

球的中心在T点,可以位于二维平面上的任何地方,除了蓝色区域。

给定C、T、P和r,有没有一种干净高效的方法来检测球T是否会干扰球C的轨迹?

我想在Python中完成这个任务,可以使用其他库如numpy或pygame。

英文:

I have the following ball configuration:

P=(115,100)
T=(253,211)
C=(389,464)
r=60

查找两个在平面上移动的球之间是否发生碰撞 Python

The ball of center C and radius r follows a straight line from C to P.

In this trajectory there might be a ball T of radius r that causes a collision with ball C and deflects ball C from its course.

Ball of center T can be anywhere in the 2D plane except the blue region

Given C, T, P, and r, what is a clean and efficient way to detect whether or not ball T will interfer with ball C trajectory?

I would like to do this in python and other libraries can be used like numpy or pygame.

答案1

得分: 1

我们可以计算从点 T 到线 CP 的距离 D

定义向量

CP = P - C

在坐标上:

cpx = P.x - C.x
cpy = P.y - C.y

并对其进行归一化:

length = math.hypot(cpx, cpy)
ucpx = cpx / length
ucpy = cpy / length

另一个向量

CT = T - C
ctx = T.x - C.x
cty = T.y - C.y

使用叉乘计算距离

D = abs(CT 叉乘 UCP)
D = abs(ctx*ucpy-cty*ucpx)

另一个值 - 向量点积的符号可以判断 T 是否位于 C 的“后方”

dtp = (CT 点积 UCP)
dtp = (ctx*ucpx+cty*ucpy)

然后将 D 与半径和(这里是半径的两倍)比较并检查点积的符号

if (D < 2*r) and (dtp > 0):
    发生碰撞
英文:

We can calculate distance D from point T to line CP.

Define vector

CP = P - C

in coordinates:

cpx = P.x - C.x
cpy = P.y - C.y

and normalize it

length = math.hypot(cpx, cpy)
ucpx = cpx / length
ucpy = cpy / length

Another vector

CT = T - C
ctx = T.x - C.x
cty = T.y - C.y

Distance using cross product

D = abs(CT x UCP)
D = abs(ctx*ucpy-cty*ucpx)

One more value - sign of dot product of vectors allows to know if T lies "behind" C

dtp =  (CT dot UCP)
dtp =  (ctx*ucpx+cty*ucpy)

Then compare D with radius sum (here doubled radius) and check sign of dot product

 if (D &lt; 2*r) and (dtp &gt; 0):
    collision occurs

huangapple
  • 本文由 发表于 2023年6月1日 01:34:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定