我的目标是使用围绕圆的边缘和恒定起点(圆圈的中间)的随机端点在pygame中使用线条形成圆形.所以我决定将pygame.draw.line函数:screen,arandomcolor,startingposition和endingposition作为参数.结束位置是包含随机生成的x值的元组,辅助函数将根据圆的半径计算y值.我的第一个函数计算y值,如下所示:
import mathimport randomdef findY(pos1,pos2,distance,bothValues=False): p1 =pos1 p2 = pos2 x1 = float(p1[0]) y1 = float(p1[1]) x2 = float(p2[0]) d = float(distance) y2 = y1 - math.sqrt(d**2 - (x1-x2)**2) _y2 = y1 + math.sqrt(d**2 - (x1-x2)**2) if bothValues==True: return y2,_y2 else: return y2
和线条抽屉:
wIDth = 500height = 500def randline(surface,color=rand,start=rand,end=rand,length=rand): if start==rand: start = randPos() if end==rand: end = randPos() if color==rand: color = randcolor() if length != rand: end_x = float(random.randint(0,wIDth)) end_pos = (end_x,"y") y2=findMissing(start_pos,end_pos,l,bothValues=True) a = random.randint(0,1) if a==0: y2 = float(y2[0]) else: y2 = float(y2[1]) lst = List(end_pos) lst[1] = y2 end_pos = tuple(lst) pygame.draw.line(surface,color,start_pos,end_pos)
然后:
drawRandline(screen,start=(200,200),lenght=100)
(那些称为randPos的其他函数不是问题).由于某种原因,这会产生一个错误,我诊断为math.sqrt()中的值是负数.但这种情况不可能发生,因为那里的每一个值都提高到2的幂,这就是我所困惑的.所以我将math.sqrt()中的值更改为其绝对值.这使得该函数不会引发任何错误,但绘制的圆圈看起来像这样:
我知道pygame的坐标平面的y值是颠倒的,但这应该有所不同吗?
最佳答案获得均匀角度分布的一种方法是生成0到2 * math.pi之间的随机角度theta,并使用三角函数来找到线的终点的坐标:def drawRandlineTrig(start_pos,length): theta = random.rand() * 2 * math.pi end_pos = (start_pos[0] + length*math.cos(theta),start_pos[1] + length*math.sin(theta)) # ...
总结 以上是内存溢出为你收集整理的python距离公式坐标平面误差全部内容,希望文章能够帮你解决python距离公式坐标平面误差所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)