Reputation: 1557
I'm trying to render simple 3d shapes (in this particular case, a cube) in a html5 canvas. Translating 3d points to a 2d plane was easy enough, so I went ahead and starting coloring the polygons. They overlap in the wrong order. So I just calculate the distance of each polygon (based on the avarage of the 4 corners) and sort them based on that.
Except that doesn't really work. So how do you decide what polygons you draw first?
P.S. I'm trying to learn how to make this, so using existing libraries or something would not really work for that.
Upvotes: 2
Views: 559
Reputation: 1557
After searching for a while, I found a way to check this. It is done through 'backface culling' and from what I understand, you first calculate the 2d positions of the polygon, then take 3 points, and compare them to determine which way the polygon faces.
the check I used is as followed:
ifVisible = function(p1, p2, p3)
{
return ((p2[0]-p1[0])*(p3[1]-p1[1])>(p3[0]-p1[0])*(p2[1]-p1[1]));
}
where p1, p2 and p3 are arrays containing the x and y positions of the points.
This only works if you have an order for the points in your polygons, (in my case, the positions are clockwise when faced towards the camera)
Upvotes: 1