加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python距离公式坐标平面误差

发布时间:2020-12-16 22:53:50 所属栏目:Python 来源:网络整理
导读:我的目标是使用围绕圆的边缘和恒定起点(圆圈的中间)的随机端点在pygame中使用线条形成圆形.所以我决定将pygame.draw.line函数:screen,aRandomColor,startingPosition和endingPosition作为参数.结束位置是包含随机生成的x值的元组,辅助函数将根据圆的半径计

我的目标是使用围绕圆的边缘和恒定起点(圆圈的中间)的随机端点在pygame中使用线条形成圆形.所以我决定将pygame.draw.line函数:screen,aRandomColor,startingPosition和endingPosition作为参数.结束位置是包含随机生成的x值的元组,辅助函数将根据圆的半径计算y值.我的第一个函数计算y值,如下所示:

import math
import random

def 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 = 500
height = 500

def 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()中的值更改为其绝对值.这使得该函数不会引发任何错误,但绘制的圆圈看起来像这样:

wacky inverted circloid

我知道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))
    # ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读