[英]How to draw a rectangle around two points
我正在使用 pygame 和數學模塊嘗試在兩個點周圍繪制一個矩形。 這就是我的意思:
從點到矩形末端的距離被指定為 class 的屬性。 我已經嘗試了很多以使其到達它的位置,並且顯示的角度可能是唯一的工作角度。 這是矩形的 class :
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)
嘗試了它,它執行了半成功:
代碼在上面,您可以嘗試使用其他值,但您會發現它很快就會出現問題。 總結一下,我的問題是,有沒有一種可靠的方法可以在給定的兩個點周圍繪制一個矩形? 我努力了:
問題是 function math.atan()
返回范圍 [-pi/2, +pi/2] 內的角度。
使用math.atan2()
(參見math )返回范圍 [-pi,+pi] 內的角度。 因此,這個 function 立即給出正確的角度,您不需要任何更正:
angle = (math.degrees(math.atan((y/x))))%360
angle = math.degrees(math.atan2(y, x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.