我正在使用pygame和math模块尝试在两点周围绘制一个矩形。这就是我的意思:
从点到矩形末端的距离被指定为该类的属性。我已经尝试了很多,以使其达到实际位置,并且所示的角度可能是唯一的工作角度。这是我的矩形课:
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) and (200, 200)
。然后,我用(300, 300) and (200, 200)
进行了尝试,并成功执行了以下操作:
上面的代码可以用其他值尝试一下,但是您很快就会发现它变得有问题。总结一下,我的问题是,是否有一种健壮的方法围绕给定的两个点绘制一个矩形?我尝试过:
答案 0 :(得分: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))