Skip to main content
 首页 » 编程设计

python之线对线与pygame的倒置y轴相交

2024年11月24日8itcoder

https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line

https://www.youtube.com/watch?v=TOEi6T2mtHo

我已尝试在我的代码中实现此方法但无济于事,我相信问题出在 pygame 中的倒置 y 轴上,或者是其他隐藏在我视线中的东西?有什么建议么?

这是我的代码:

        x1 = other.pos1[0] 
        y1 = other.pos1[1] 
        x2 = other.pos2[0] 
        y2 = other.pos2[1] 
 
        x3 = self.pos1[0] 
        y3 = self.pos1[1] 
        x4 = self.pos2[0] 
        y4 = self.pos2[1] 
 
        den = (x1 - x2) * (y3 - y4) - (y1 * y2 * (x3 - x4)) 
 
        if den == 0: 
            return 
 
        t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den 
 
        u = -(((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3))) / den 
 
        if t > 0 and t < 1 and u > 0: 
            point = (x3 + u * (x4 - x3), y3 + u * (y4 - y3)) 
 
            pygame.gfxdraw.filled_circle(surface, point[0], point[1], 3, (255, 0, 0)) 
 
            return point 
 
        else: 
            return 

请您参考如下方法:

Line–line intersection 的分母由公式计算:

(x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4). 

所以下面的表达式是错误的:

den = (x1 - x2) * (y3 - y4) - (y1 * y2 * (x3 - x4)) 

它必须是:

den = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))