简体   繁体   中英

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. 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". However whenever i try to create this, it just seems to stay in a 2d setting.

For example, the 2d method to do this is below, and i want the 3d to be the same consisting of a 16x16 grid

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.

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:

  • use the WEBGL renderer (eg canvas(400, 400, WEBGL); )
  • use box() instead of rect()
  • use push() / pop() and translate(x, y, z) to draw boxes at the grid coordinates

You can use camera() function to angle the get that perspective. (You can optionally also use rotateY() , rotateX() calls to rotate the whole coordinate space, but using camera() will preserve the original coordinate system)

 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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