Webgl Vector Array

javascript, vector, webgl

Solution

The problem is the following line:

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

`new Float32Array(vertices)` is returning `[NaN, NaN, NaN]`. This is because the `Float32Array` contructor expects an array of `Number`s and not an array of `Vector`s.

You'll need to pass `new Float32Array()` a single one dimensional array of `Number`s

If you want to fix it you'll have to write a function to convert your array of `Vector`s into a `Float32Array`. Something like this:

function vectorsToFloatArray(vertices) {
    var numbers = [];

    for(var i = 0; i < vertices.length; i++) {
        numbers.push(vertices[i].x);
        numbers.push(vertices[i].y);
        numbers.push(vertices[i].z);
    }

    return new Float32Array(numbers);
}

And remember to update the `gl.bufferData()` and item size:

    gl.bufferData(gl.ARRAY_BUFFER, vectorsToFloatArray(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3;

Problem

I am trying to make A cube of triangles using JavaScript and Webgl. The cube will use face edge vertex structure using arrays , but when I use arrays there is nothing drawn to screen. This how I declare the array. ``` function Vector(x,y,z){ this.x = x; this.y = y; this.z = z; } var V = new Array; V[0] = new Vector(0.0, 1.0, 0.0); V[1] = new Vector(-1.0, -1.0, 0.0); V[2] = new Vector(1.0, -1.0, 0.0); function initBuffers() { triangleVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); var vertices = [ V[0], V[1], V[2] ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); triangleVertexPositionBuffer.itemSize = 1; triangleVertexPositionBuffer.numItems = 3; ``` I am not sure why it doesn't draw to screen if anyone can help it would be appreciated.

Original source