Detecting Rectangle collision with a Circle

前端 未结 3 546
遥遥无期
遥遥无期 2021-01-07 08:45

I have a Circle with a center point (Center_X, Center_Y) and I am detecting if a rectangle falls into it\'s Radius (Radius). How would I be able to perform this task? I ha

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 09:37

    Use the dist function from Shortest distance between a point and a line segment

    import math
    
    def dist(p1, p2, c): 
        x1,y1 = p1
        x2,y2 = p2
        x3,y3 = c
        px = x2-x1
        py = y2-y1
    
        something = px*px + py*py
    
        u =  ((x3 - x1) * px + (y3 - y1) * py) / float(something)
    
        if u > 1:
            u = 1
        elif u < 0:
            u = 0
    
        x = x1 + u * px
        y = y1 + u * py
    
        dx = x - x3
        dy = y - y3
    
        dist = math.sqrt(dx*dx + dy*dy)
    
        return dist
    

    Here is a test:

    rect = [[0. ,  0. ],
           [ 0.2,  1. ],
           [ 2.2,  0.6],
           [ 2. , -0.4]]
    
    c = 0.5, 2.0
    r = 1.0
    
    distances = [dist(rect[i], rect[j], c) for i, j in zip([0, 1, 2, 3], [1, 2, 3, 0])]
    print distances
    print any(d < r for d in distances)
    

    output:

    [1.044030650891055, 1.0394155162323753, 2.202271554554524, 2.0592194189509323]
    False
    

    Here is the plot:

    enter image description here

提交回复
热议问题