p5.js项目求助:Building类生成的3D盒子无法均匀排列
p5.js 3D盒子非均匀间距问题解决
你的问题核心出在坐标变换的顺序与累积效应上:
- 当前代码先绘制盒子再执行
translate,而p5.js WEBGL模式下的坐标变换是全局累积的——第一个盒子绘制后,坐标系被偏移;第二个盒子会基于偏移后的新坐标系绘制,之后又再次偏移,以此类推,位移不断叠加,最终出现间距越来越大的“非均匀”效果。 - 没有用
push()/pop()隔离每个建筑的绘制上下文,导致坐标变换互相干扰。
解决方案
修改Building类的create()方法,调整操作顺序并隔离坐标变换,同时修正位置计算逻辑,确保建筑居中且均匀分布:
let buildings = [] class Building { constructor(spot, h, w, spacing) { this.spot = spot; this.h = h; this.w = w; this.spacing = spacing; } create() { push(); // 保存当前坐标系状态,隔离后续变换 // 计算居中的X位置:spot从0到4,中间点为2,以此为基准向两侧偏移 translate((this.spot - 2) * this.spacing, 0, 0); box(this.w, this.h, this.w); pop(); // 恢复原坐标系,不影响其他建筑绘制 } } function setup() { createCanvas(800, 600, WEBGL); const spacing = 160; // 自定义建筑间距 for (let i = 0; i < 5; i++) { buildings[i] = new Building(i, 400, 40, spacing); } } function draw() { background(220); for (let building of buildings) { building.create(); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
关键细节说明
push()和pop()是核心:它们会为每个建筑创建独立的绘制上下文,确保translate只作用于当前建筑,不会干扰其他元素。- 位置计算调整为
(this.spot - 2)*this.spacing:5个建筑的spot取值0-4,以中间值2为基准偏移,能让整体布局自动居中,左右建筑均匀分布。 - 若要调整Y/Z轴位置,直接修改
translate的对应参数即可,每个建筑的坐标变换都是独立的,不会出现位置混乱。
内容的提问来源于stack exchange,提问作者Daniel Portillo
相关产品推荐
相关产品推荐

