在我需要的时候,我无法找到关于这个主题的文章或stackoverflow问题。
我正在制作2D游戏,我想生成一个随机形状的小行星。每个小行星都有一个中心,一个X, Y
位置,我想生成让我们说它周围有8个顶点(顶点的数量是可变的)
如果我现在可以实现这个形状,我想添加一个随机元素,让我们说一个变量和距离中心的随机距离,以创建一个随机的岩石形状。
我研究了一些名为Polar的三角概念到 Cartisian Coordinates 但是还没有弄清楚如何将它应用到这个目标。虽然在Javascript中有它的教程,它使用我必须从头开始在python中创建的库和函数。
修改 所以你的答案主要集中在解释中心周围顶点的公式,这些是我已经知道的事情,
1)在我正在使用的图形库中绘制一个多边形 2)获取随机数
提前非常感谢你!
答案 0 :(得分:6)
您可以使用random
库随机采样极坐标。采样方向,然后采样径向距离。在下面的例子中,我选择了方向将在[0, 2*pi]
中均匀分布,并且半径将正常分布为用户输入均值和标准差。
import random
import math
def generate_points(center_x, center_y, mean_radius, sigma_radius, num_points):
points = []
for i in range(num_points):
theta = random.uniform(0, 2*math.pi)
radius = random.gauss(mean_radius, sigma_radius)
x = center_x + radius * math.cos(theta)
y = center_y + radius * math.sin(theta)
points.append([x,y])
return points
作为如何调用它的一个例子
>>> generate_points(5.0, 7.0, 1.0, 0.1, 8)
[[4.4478263120757875, 6.018608023032151],
[4.407825651072504, 6.294849028359581],
[5.0570272843718085, 6.17834681191539],
[5.307793789416231, 6.156715230672773],
[4.368508167422119, 7.712616387293795],
[5.327972045495855, 5.917733119760926],
[5.748935178651789, 6.437863588580371],
[3.9312163910881033, 6.388093041756519]]
如果你想让点按特定的顺序缠绕,那么我会使用像numpy.linspace
这样的东西来顺时针或逆时针走动来采样theta。例如
import random
import math
import numpy as np
def generate_points(center_x, center_y, mean_radius, sigma_radius, num_points):
points = []
for theta in np.linspace(0, 2*math.pi - (2*math.pi/num_points), num_points):
radius = random.gauss(mean_radius, sigma_radius)
x = center_x + radius * math.cos(theta)
y = center_y + radius * math.sin(theta)
points.append([x,y])
return points
如果您不想安装numpy
,可以编写自己类似版本的linspace
def linspace(start, stop, num_steps):
values = []
delta = (stop - start) / num_steps
for i in range(num_steps):
values.append(start + i * delta)
return values
答案 1 :(得分:0)
一种简单的方法是随机选择一个或两个或三个非相邻顶点,并简单地移动它们一个随机数量,该数量不超过距离最近顶点的距离。