Javascript 如何使此多边形渲染为完整形状而不是新月形?

Javascript 如何使此多边形渲染为完整形状而不是新月形?,javascript,webgl,Javascript,Webgl,我正在使用下面的javascript函数来创建一个顶点数组,以便在创建形状时传递到缓冲区。它应该计算第一个顶点位于原点的n边正多边形的顶点。然后创建缓冲区并将其作为属性存储在传递给函数的shape对象上 var vertices = []; // Create each vertex by calculating the position of the new vertex relative // to the old then adding on to the old position /

我正在使用下面的javascript函数来创建一个顶点数组,以便在创建形状时传递到缓冲区。它应该计算第一个顶点位于原点的n边正多边形的顶点。然后创建缓冲区并将其作为属性存储在传递给函数的shape对象上

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);
var顶点=[];
//通过计算新顶点的相对位置来创建每个顶点
//对旧的位置,然后添加到旧的位置
//首先在原点设置第一个顶点
顶点[0]=0.0;
顶点[1]=0.0;
顶点[2]=0.0;
var-oldX=0.0;
var oldY=0.0;
对于(var i=0;i
这对于三角形来说绝对有效,但是对于五边形或更高的三角形来说,形状是不完整的——它看起来像一个新月。我在下面包括了一个工作三角形和一个非工作六边形的屏幕截图,它们都是用相同的函数创建的

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


有人能看出我做错了什么吗?

画出三个垂直方向,你应该有一个想法-现在你正在这样做:

(V1, V2, V3) -> Triangle along an edge
(V2, V3, V4) -> Another triangle along an edge.
(V3, V4, V5) -> Another triangle along an edge.
当你这样做的时候,没有三角形穿过中心,你得到的是你贴的新月形

要正确地绘制它,您需要这样做:(固定每个三角形的1点,并围绕边移动其他两点)


这有一个示例图像供参考:

首先以原点为中心绘制多边形。然后你的顶点是sin,cos,theta和一个与边长成比例的值的简单函数(你可以使用余弦定律的一个变体来找到它)。然后,将所有点按相同比例移动,使第一点位于原点。@Scott-谢谢你的想法!这将使计算变得简单得多。