英文:
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
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 < 2*r) and (dtp > 0):
collision occurs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论