简体   繁体   English

P5.JS 创建 3d 网格

[英]P5.JS Create 3d Grid

I know of the way in p5.js to create a grid of squares/rect in 2d, however i cannot seem to be able to create this in p5's 3d setting using webGL.我知道在 p5.js 中创建二维正方形/矩形网格的方式,但是我似乎无法使用 webGL 在 p5 的 3d 设置中创建它。 I am trying to create a 3d grid "of size 50x50x50 from -400 to 400 in the x-axis and -400 to 400 on the z-axis".我正在尝试创建一个 3d 网格“大小为 50x50x50,x 轴为 -400 到 400,z 轴为 -400 到 400”。 However whenever i try to create this, it just seems to stay in a 2d setting.但是,每当我尝试创建它时,它似乎都停留在 2d 设置中。

For example, the 2d method to do this is below, and i want the 3d to be the same consisting of a 16x16 grid例如,执行此操作的 2d 方法如下,我希望 3d 与由 16x16 网格组成的相同

function setup() {
  createCanvas(400, 400);

  background(220);
  
  for (let x=0;x<width;x+=20){
    for (let y=0;y<height;y+=20){
        rect(x,y,20,20); 
    }
  }
}

Any help adjusting this code to bring it to 3d would help massively, Ive looked around and cannot find any help on how to do this Im brand new to 3d primitives and webgl so help would be greatly appreciated.调整此代码以将其带到 3d 的任何帮助都会有很大帮助,我环顾四周,找不到任何有关如何执行此操作的帮助我对 3d 原语和 webgl 是全新的,因此将不胜感激。

Below is how I am trying to get it to look下面是我试图让它看起来

我希望网格看起来如何的图像

Im aware, camera adjusting would ne needed also, but just wanted to take one step at a time.我知道,相机调整也需要,但只是想一次迈出一步。

Thanks again再次感谢

You're on the right track, just need 3 ingredients:你在正确的轨道上,只需要 3 种成分:

  • use the WEBGL renderer (eg canvas(400, 400, WEBGL); )使用WEBGL渲染器(例如canvas(400, 400, WEBGL);
  • use box() instead of rect()使用box()而不是rect()
  • use push() / pop() and translate(x, y, z) to draw boxes at the grid coordinates使用push() / pop()translate(x, y, z)在网格坐标处绘制框

You can use camera() function to angle the get that perspective.您可以使用camera() function 来调整角度。 (You can optionally also use rotateY() , rotateX() calls to rotate the whole coordinate space, but using camera() will preserve the original coordinate system) (您也可以选择使用rotateY() 、 rotateX( rotateX()调用来旋转整个坐标空间,但使用camera()将保留原始坐标系)

 function setup(){ createCanvas(400, 400, WEBGL); background(220); camera(-200, -200, -200, // camera position (x, y, z) 0, -100, 0, // camera target (look at position) (x, y, z) 0, 1, 0); // camera up axis: Y axis here for (let x=0; x < width; x +=20){ for (let z=0; z < height; z +=20){ push(); // ground plane is XZ, not XY (front plane) translate(x, 0, z); box(20); pop(); } } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

Optionally you could offset the position of each box based on the centre of the grid so further transformations to the grid will occur from the centre (and not from a corner).或者,您可以根据网格的中心偏移每个框的 position,以便从中心(而不是从角落)对网格进行进一步的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM