문제

I'm writing a simple 2D top-down game in Python 3 using tkinter. All the collidable objects are either circles/arcs or lines. I wrote the following method to detect when a circle hits a line:

I am using the formulas y = mx + b and r^2 = (x-h)^2 + (y-k)^2

def CheckHitCToL(self, LX0, LY0, LX1, LY1, CX0, CX1, Tab):
    try:
        H = self.Creatures[Tab].X
        K = self.Creatures[Tab].Y
        R = abs((CX0 - CX1) / 2)
        M = (LY0 - LY1) / (LX0 - LX1)
        B = M * (-LX1) + LY1
        QA = (M * M) + 1
        QB = (-H - H) + (((B - K) * M) * 2)
        QC = (H * H) + ((B - K) * (B - K)) - (R * R)
        X = (- QB + sqrt((QB * QB) - (4 * QA * QC))) / (2 * QA)
        Y = (M * X) + B
        if ((X <= LX0 and X >= LX1) or (X >= LX0 and X <= LX1)) and ((Y <= LY0 and Y >= LY1) or (Y >= LY0 and Y <= LY1)):
            return True
        else:
            return False
    except:
        return False

My problem is when you have a vertical line, M (Or the slope) is (LY0 - LY1) / 0. (This is because the slope is equal to rise/run, and vertical lines don't have a run, just a rise) Which of course returns an error, caught by try except, which then informs my movement method that no collision has taken place. Of course I can simply move the "try:" down a few lines, but it's still going to throw an error. How can I adapt this program to not throw an error when working with a vertical line?

도움이 되었습니까?

해결책

Well, the most obvious method would involve using if( (LX0 - LX1)==0 ) and doing this case separately. In such cases, you need to check whether distance between LX0 and CX0 is equal to the radius of circle.

다른 팁

You can use another forms of line equation -

implicit A*x + B*y + C = 0

or parametric x = LX0 + t * (LX1 - LX0), y = LY0 + t *(LY1 - LY0)

with appropriate modification of calculations

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top