如何优化此方法以检测圆点碰撞?

2024-03-29 05:05:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个python方法,它应该返回两个接触圆的截取坐标(碰撞点)。该方法的工作原理与预期一致,但其成本似乎过高。你知道吗

应该只有一个截取点,这些圆的大小可能会有所不同。你知道吗

def getPointOfContact(self, body):
    a1 = min(self.pos.x, body.pos.x) # The x value of the centre of the left-most circle
    b1 = min(self.pos.y, body.pos.y) # The y value of the up-most circle
    a2 = max(self.pos.x, body.pos.x) # The x value of the right-most circle
    b2 = max(self.pos.y, body.pos.y) # The y value of the down-most circle
    dx = a2-a1 # (Delta x) The difference in x positions
    dy = b2-b1 # (Delta y) The difference in y positions
    if dy == 0: # In case of no difference in y,
        m = 0 # Gradient is "zero"
    elif dx == 0: # In case of no difference in x,
        m = float("inf") # Gradient is "infinity"
    else:
        m = dy/dx # Gradient
    if a1 == self.pos.x: # Such that left-most circle's radius is used
        r1 = (self.size.x)/2
    else:
        r1 = (body.size.x)/2
    # Calculates the x position of intersection using trig
    x = a1+(r1*math.cos(math.atan(m))) 
    if b1 == self.pos.y: # Such that up-most circle's radius is used
        r1 = (self.size.x)/2
    else:
        r1 = (body.size.x)/2
    # Calculates the y position of intersection using trig
    y = b1+(r1*math.sin(math.atan(m)))
    return (int(x), int(y)) # Returns the coordinates as a tuple of integers

实际上,实际计算是相当直接的。它只是将半径位移的x和y分量加到圆心的坐标上。你知道吗

问题是,为了使计算结果有效,必须有很多地方,即所使用的圆必须有最小的分量,半径(r1)与圆非常匹配。你知道吗

有没有一种方法可以简化这个方法,或者甚至可以降低整个技术的成本?你知道吗

提前谢谢。你知道吗


Tags: ofthe方法inposselfmostvalue
1条回答
网友
1楼 · 发布于 2024-03-29 05:05:03

我不太明白。你有第一个圆的半径,你假设它们正好相切,对吗?那就扔掉你的cossinatan

d = sqrt(d1**2 + d2**2)
x = a1 + dx * r1 / d
y = b1 + dy * r1 / d

看看这个三角形,+是中心,*是交点:

  0<-dx->|      
0 +
^  \ r1
|   \
|    *   d = r1+r2 = sqrt(dx**2 + dy**2)
dy    \ 
|      \ r2
v       \
-        +

注1:如果m=dy/dx并且您试图计算atan(m),那么您最好直接使用^{},它将处理恼人的零和无穷大。你知道吗

注2:cos(atan(dy/dx))==dx/RR=sqrt(dx**2+dy**2)相同,与sindy相同,因为atan(dy/dx)dx = R*cos(theta)dy = R*sin(theta)的角度。你知道吗

注3:您正在将事物投射到int,因此您的圆和交点可能有点偏离。你知道吗

相关问题 更多 >