Processing中如何在线段上生成均匀分布的点?
在Processing中在线段上生成6个均匀分布点的实现
以下是直接可用的Processing代码,实现你需要的功能:
void setup() { size(800, 600); noLoop(); // 只运行一次绘制 } void draw() { background(255); // 定义线段的两个端点:起点(0, y1),终点(width, y2) float y1 = random(height); float y2 = random(height); // 绘制原线段,方便观察 stroke(0, 100); line(0, y1, width, y2); // 要生成的均匀分布点数量 int numPoints = 6; // 循环生成每个点 stroke(255, 0, 0); strokeWeight(8); for (int i = 0; i < numPoints; i++) { // 计算当前点在线段上的比例t(0到1之间) float t = i / (float)(numPoints - 1); // 通过线性插值计算点的坐标 float x = lerp(0, width, t); float y = lerp(y1, y2, t); // 绘制点 point(x, y); } }
关键逻辑说明
- 线段定义:起点固定为
(0, random(height)),终点固定为(width, random(height)),通过random(height)随机获取两端的y轴坐标 - 均匀分布实现:用变量
t表示点在线段上的位置比例,从0(起点)到1(终点)均匀步进。因为要生成6个点,所以步进间隔是1/(6-1)=0.2,通过i/(numPoints-1)计算每个点的t值 - 坐标计算:使用Processing内置的
lerp()函数完成线性插值,根据t值计算出对应点的x和y坐标,也可以手动用公式x = 0 + t*(width-0)、y = y1 + t*(y2-y1)替代
内容的提问来源于stack exchange,提问作者FUT
相关产品推荐
相关产品推荐

