python距离公式坐标平面误差

Vit*_*you 5 python pygame distance

我的目标是使用围绕圆的边缘和恒定起点(圆圈的中间)的随机端点在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
Run Code Online (Sandbox Code Playgroud)

和线条抽屉:

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)
Run Code Online (Sandbox Code Playgroud)

然后:

drawRandLine(screen,start=(200,200),lenght=100)
Run Code Online (Sandbox Code Playgroud)

(那些称为randPos的其他函数不是问题).由于某种原因,这会产生一个错误,我诊断为math.sqrt()中的值是负数.但这种情况不可能发生,因为那里的每一个值都提高到2的幂,这就是我所困惑的.所以我将math.sqrt()中的值更改为其绝对值.这使得该函数不会引发任何错误,但绘制的圆圈看起来像这样:

古怪的倒圆形

我知道pygame的坐标平面的y值是颠倒的,但这应该有所不同吗?

Gal*_*lax 3

获得角度均匀分布的一种方法是在和theta之间生成一个随机角度,并使用三角学来查找直线终点的坐标:02 * math.pi

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))
    # ...
Run Code Online (Sandbox Code Playgroud)