简体   繁体   English

如何获取角度以在python中旋转线

[英]How to get the angle to rotate a line in python

I have a line declared with two points [x1,y1,x2,y2] and I have a new point (Nx,Ny) to which I have to first rotate the line and then move it towards it. 我有一条声明有两个点[x1,y1,x2,y2]的线,并且我有一个新点(Nx,Ny),必须首先旋转该线然后向其移动。

Here´sa picture to get it clear: 这是一张清晰的图片: 在此处输入图片说明

I have tried with this function but I can´t manage to accomplish the rotation, I´m using TkInter and Python: 我已经尝试过使用此功能,但是我无法完成旋转,我正在使用TkInter和Python:

   def rotateLine(self,dx,dy): # x and y are the differences between x1,nx and y1,ny 
          angle= math.atan2(dy,dx)
          print "angle",angle
          newx = ((x1)*math.cos(angle)-(y1)*math.sin(angle))
          newy = ((x1)*math.sin(angle)+(y1)*math.cos(angle))
          self.panel.coords(self.robot,newx,newy,newx+10,newy+30) # I always add 10 in x and 30 in y to maintain de size of the line
          self.panel.update()

I'm not familiar with TkInter, but by making an educated guess it seems that the inputs to self.panel.coords are the handle for the line and the four co-ordinates. 我对TkInter并不熟悉,但是通过有根据的猜测,似乎self.panel.coords的输入是该直线和四个坐标的句柄。 By setting the co-ords to (x,y,x+10,y+30), you are always going to have a line segment of the same length AND angle, the only thing you are actually setting is the origin of the line. 通过将坐标设置为(x,y,x + 10,y + 30),您将始终具有相同的长度和角度的线段,实际上唯一要设置的是线的原点。

Are you supposed to stretch the line from (x1,y1) to (nx,ny) or move the segment along the line between the points? 您是否应该将线从(x1,y1)延伸到(nx,ny)或沿着线段之间的点移动线段?

Also, when you calculate newx and newy, you need to centre it about the point (x1,y1). 同样,在计算newx和newy时,需要将其围绕点(x1,y1)居中。 Therefore, each place you have (x1), you need (x2-x1), and similar for y1. 因此,您拥有的每个位置(x1),需要的位置(x2-x1)和y1的相似位置。 You also then need to add x1 and y1 back in, because the formula you are using is for a rotation about the origin. 然后,您还需要重新添加x1和y1,因为您使用的公式是围绕原点旋转的。 The equations should then be 方程应该是

newx = ((x2-x1)*math.cos(angle)-(y2-y1)*math.sin(angle)) + x1
newy = ((x2-x1)*math.sin(angle)+(y2-y1)*math.cos(angle)) + y1

If the first thing you want to do is rotate the line segment towards the new point, then you should try 如果您要做的第一件事是将线段朝新点旋转,则应尝试

self.panel.coords(self.robot,x1,y1,newx,newy)

The preservation of the length of the line should have been preserved in your calculation of the new point. 在计算新点时,应该保留线的长度。 Moving the line segment is a simple matter of translating both points using the angle from the vertical and by the distance between (newx,newy) and (Nx,Ny). 移动线段很简单,只需使用与垂直线的角度以及(newx,newy)与(Nx,Ny)之间的距离来平移两个点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM