如何在两个点之间画一个矩形

5
我正在使用pygame和math模块尝试在两个点周围绘制矩形。这就是我的意思:

Rectangle-controlled-by-two-points

矩形的端点到点的距离被指定为类的属性。我已经尽力使其达到目前的状态,所显示的角度可能是唯一有效的角度。以下是我的矩形类:

def Pol(x, y):
    """Converts rectangular coordinates into polar ones"""
    if x == 0: # This might be the source of my problems, but without it, it raises ZeroDivisionErrors at certain places
        if y >= 0:
            return [y, 90]
        else:
            return [-y, 270]
    r     = math.sqrt(x**2+y**2)
    angle = (math.degrees(math.atan((y/x))))%360
    return [r, angle]

class Path(pygame.sprite.Sprite):
    def __init__(self, start, end, color, width, **options):
        self.__dict__.update(options)
        self.start = start
        self.end = end
        self.color=color
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the blob, and its x and y position, width and height
        # Set the background color and make it transparent
        self.width = width

        # Draw the path
        self.redraw()

        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = (self.start[0]-self.width//2+self.ix,
                                    self.start[1]-self.width//2+self.iy)
        if self.inversed:
            self.rect.y-=(math.ceil(self.image.get_rect()[3]/2)-self.iy)

    def redraw(self):
        dis, angle = Pol(self.end[0]-self.start[0], self.end[1]-self.start[1])
        dis += self.width
        _image = pygame.Surface([dis, self.width])
        _image.fill([255, 255, 255])
        _image.set_colorkey([255, 255, 255])
        pygame.draw.rect(_image, self.color, pygame.Rect(0, 0, dis, self.width))
        nangle = (180-angle)%360
        self.inversed = nangle>=180
        self.image = pygame.transform.rotate(_image, nangle)
        i1 = _image.get_rect()
        i2 = self.image.get_rect()
        ix = i2[2]-i1[2]
        iy = i2[3]-i1[2]
        self.ix = ix//2
        self.iy = iy//2

所以,我传递了一些点给它,它负责所有繁重的工作和绘图。我在图像中传递给它的点是(100, 100)和(200, 200)。然后我尝试使用(300, 300)和(200, 200),结果半成功:

failed test

这是代码,你可以尝试使用其他值,但你会发现它很快变得有问题。总之,我的问题是,是否有一种强大的方法来绘制给定两点之间的矩形?我已经尝试过:

  • 使用粗线条进行绘制,但pygame的线条在某些角度上会断开,并且具有水平端点
  • 反复测试和尝试不同的值,但我尝试的所有方法都无效
  • 更改反向if语句。根据我认为应该发生的事情,它已经是反向的了

因此,规则是矩形的主轴应与通过这两个点的直线对齐,并且它应该足够宽/高,以包含该线段以及每侧特定数量的额外部分? - Karl Knechtel
你是正确的。 - User 12692182
1个回答

5
问题在于函数math.atan()返回的角度范围为[-pi/2,+pi/2]。
使用math.atan2()(请参见math),它返回的角度范围为[-pi,+pi]。因此,这个函数一次就给出了正确的角度,你不需要进行任何更正:

angle = (math.degrees(math.atan((y/x))))%360

angle = math.degrees(math.atan2(y, x))

另请参阅C++中 atan 和 atan2 的区别是什么?


2
一些背景阅读(Python函数与C函数相似),请参考以下链接:https://dev59.com/pXVC5IYBdhLWcg3weA8- - Karl Knechtel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接