简体   繁体   中英

Javascript matrix multiplication by scalar

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. Ie when i hits 72 the loop does not stop.

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. Ie 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM