python距离公式坐标平面误差

标签 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

和线抽屉:

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 值是颠倒的,但这会有什么不同吗?

最佳答案

获得均匀分布角度的一种方法是在 02 * 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距离公式坐标平面误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33988720/

相关文章:

python - Pygame:当 Sprite 遇到它的踪迹时如何 "lose"游戏

python - 在pygame中旋转一个矩形

r - PCA空间和 'feature-space'发散中的质心距离计算

python - Google App Engine 本地开发服务器不路由到远程云存储桶

Python 3.4 将列表写入 csv

python - 将重复参数传递给 Numpy 向量化函数的最佳方法

python - pip安装pygame-找不到SDL.h文件

python - 寻找最大和距离

elasticsearch - Elasticsearch 5.x 中地理距离查询的返回距离

python - 使用 python subprocess.popen ..无法阻止 exe 停止工作提示