Javascript matrix multiplication by scalar

474 views Asked by At

I have an object called Cube. It is set up like this

//Cube object
    function Cube(vertices, color, scale) 
    {
        //this.vertices = vertices;
        this.setColor(color);
        this.setScale(vertices, 1);
    }

I commented out //this.vertices = vertices; because im not sure if I have to set vertices here or set them within setScale() function.
I want to set a scale on a matrix. The matrix is:

var verts = [
            // Front face
            -1.0, -1.0,  1.0,
             1.0, -1.0,  1.0,
             1.0,  1.0,  1.0,
            -1.0,  1.0,  1.0,

            // Back face
            -1.0, -1.0, -1.0,
            -1.0,  1.0, -1.0,
             1.0,  1.0, -1.0,
             1.0, -1.0, -1.0,

            // Top face
            -1.0,  1.0, -1.0,
            -1.0,  1.0,  1.0,
             1.0,  1.0,  1.0,
             1.0,  1.0, -1.0,

            // Bottom face
            -1.0, -1.0, -1.0,
             1.0, -1.0, -1.0,
             1.0, -1.0,  1.0,
            -1.0, -1.0,  1.0,

            // Right face
             1.0, -1.0, -1.0,
             1.0,  1.0, -1.0,
             1.0,  1.0,  1.0,
             1.0, -1.0,  1.0,

            // Left face
            -1.0, -1.0, -1.0,
            -1.0, -1.0,  1.0,
            -1.0,  1.0,  1.0,
            -1.0,  1.0, -1.0
        ];

The function i use to set the scale is like this:

Cube.prototype.setScale = function(vertices, scale) 
    {
        var length = vertices.length;
        for( var i = 0; i < length; i++)
        {
            //alert("before "+ vertices[i]+ " i "+ i);
            vertices[i] *= scale; 
            //alert("after "+ vertices[i]);
        }

I think that by doing this the for loop should take the matrix length and start a for loop.
Within this for loop I will get the vertice at i and multiply it by the scale.
When I do it like this though the for loop will reiterate. I.e. when i hits 72 the loop does not stop.

1

There are 1 answers

1
Jason S On BEST ANSWER

I commented out //this.vertices = vertices; because im not sure if I have to set vertices here

You either need to set it there or at the end of the constructor. Your setScale function is nicely decoupled from where the vertices array is stored and I'd keep it that way. But you might consider renaming it scaleVertices() instead.

When I do it like this though the for loop will reiterate. I.e. when i hits 72 the loop does not stop.

Really? That's odd. I must be missing something; the code looks correct.

Don't use alert(), by the way, it will make your life hell to debug anything. You're much better using console.log().