1

I'm using the following javascript function to create an array of vertices to pass to a buffer when creating a shape. It should calculate the vertices of an n-sided regular polygon with the first vertex located at the origin. The buffers are then created and stored as properties on the shape object that was passed to the function.

var vertices = [];

// Create each vertex by calculating the position of the new vertex relative
// to the old then adding on to the old position

// Begin by setting up the first vertex at the origin

vertices [0] = 0.0;
vertices [1] = 0.0;
vertices [2] = 0.0;

var oldX = 0.0;
var oldY = 0.0;

for (var i = 0; i < shape.numberOfSides; i++) {
    var theta = i * 2 * Math.PI / shape.numberOfSides;
    var y = shape.sideLength * Math.sin(theta);
    var x = shape.sideLength * Math.cos(theta);

    y += oldY;
    x += oldX;

    var start = (i+1) * 3;
    vertices [start] = x;
    vertices [start + 1] = y;
    vertices [start + 2] = 0.0;

    oldX = x;
    oldY = y;

}

// Create a buffer and store the vertices on it

shape.verticesBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, shape.verticesBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

This works absolutely fine for triangles, but for pentagons or above the shape is not complete - it looks like a crescent. I've included a screenshot below of the working triangle and a non-working hexagon, both created with the same function.

http://i39.tinypic.com/ndoj8z.png

Can anyone see what it is that I'm doing wrong?

Emma
  • 335
  • 1
  • 4
  • 13
  • 1
    Start by drawing your polygon centered on the origin. Then your vertices are simple functions of sin, cos, theta, and a value that is proportional to sideLength (you can use a variant of the Law of Cosines to find it). Then, shift all the points over by that same proportion so that the first point is on the origin. – Scott Mermelstein Oct 28 '13 at 21:59
  • @Scott - Thank you for the idea! That would make it a lot simpler to work out. – Emma Oct 28 '13 at 22:03

1 Answers1

3

Draw 1 trio of verticies and you should get an idea - Right now you're doing this:

(V1, V2, V3) -> Triangle along an edge
(V2, V3, V4) -> Another triangle along an edge.
(V3, V4, V5) -> Another triangle along an edge.

When you do that, no triangle ever passes through the center and you get the crescent you posted.

To draw it properly, you need to do this: (Fix 1 point of every triangle and move the other two points around the edge)

(V1, V2, V3)
(V1, V3, V4)
(V1, V4, V5)

This has an example image for reference : Drawing GL Polygons

Community
  • 1
  • 1
Josh B
  • 1,748
  • 16
  • 19