2014-11-09 54 views
0

我目前遇到了任務問題,並且一直在努力查明幾個小時的錯誤。使用三角函數計算矩形的新中心

我有一個圓形和一個矩形(均由用戶點擊繪製)。如圖所示:

i.stack.imgur(點)的COM/4aXIw.png

使用矩形的中心點,我要計算一個新的中心點(矩形),其位於該圈。我通過計算角度(theta)並使用三角學得到新的中心點來實現這一點。

i.stack.imgur(點)的COM/NoCBS.png

然而,當我運行我的程序,我沒有得到正確的結果。如下圖所示:

i.stack.imgur(點)的COM/ZG9Ld.png

我已經簽了一百次,我似乎無法準確判斷我搞砸了。我檢查了θ,並且得出的度數是正確的。下面是相關的代碼,在那裏我懷疑我犯了一個錯誤:

theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x)) 
theta = int(math.degrees(theta)) 

rec_x = click1.x + radius*math.cos(theta) 
rec_y = click1.y + radius*math.sin(theta) 

以下是完整的代碼,如果你想運行它:

from graphics import * 
import math 

def main(): 

#setup window 
win = GraphWin("Traveling Rectangle",600,450) 
win.setCoords(0,0,600,450) 

click1 = win.getMouse() 
click2 = win.getMouse() 
radius = click2.x - click1.x 
circle = Circle(click1, radius) 
circle.draw(win) 

click3 = win.getMouse() 
click4 = win.getMouse() 
rect = Rectangle(click3, click4) 
rect.draw(win) 
rect.setFill("red") 
rect.setOutline("red") 

#the centerpoint of the initial rectangle 
initialrec_x = (click3.x + click4.x)/2 
initialrec_y = (click3.y + click4.y)/2 

#the trig to calculate the point on the circle 
theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x)) 
theta = int(math.degrees(theta)) 

#the new centerpoint values of x and y 
rec_x = click1.x + radius*math.cos(theta) 
rec_y = click1.y + radius*math.sin(theta) 

main() 

幫助將不勝感激!

我很抱歉,該網站沒有讓我發佈圖片。圖形庫可以在這裏找到:mcsp.wartburg(點)埃杜/ zelle /蟒蛇/ graphics.py

+0

我沒有看到任何改變矩形座標或重畫的東西。 – 2014-11-09 04:39:15

+1

'math.cos()'和'math.sin()'想要的參數是弧度而不是度數。另外,'math.atan()'不太可能在上象限之外工作。你可能想要'math.atan2()'。 – Tony 2014-11-09 04:42:45

回答

0

我使用的是不同的圖形軟件包,但對我來說了以下工作:

... 
initialrec_y = (click3.y + click4.y)/2 

theta = math.atan2(initialrec_y - click1.y, initialrec_x - click1.x) 
rec_x = click1.x + radius * math.cos(theta) 
rec_y = click1.y + radius * math.sin(theta) 

這使用atan2函數,該函數記錄下yx輸入的符號,以正確計算該點所在的象限並相應地返回一個角度。除此之外,與您的代碼唯一的區別是沒有弧度(atan2返回)轉換爲度數。 sincos想要弧度。