Pris0n
Pris0n

Reputation: 350

Object in Array, copy not reference

Here is what I have: particles is an array full of particle objects. Currently I just add references of the object to the array, so after the loop ends every object has the same velocity values. But I want different for each one. What needs to be done, that there are actual objects in the array and not just references to the object?

for (i = 0; count > i; i++){
    var particle = this.model; //object i want to have multiple clonse from
    particle.velocity = vec3.create(); //vec3.create from glmatrix library
    var x = Math.random() * (0.1 - (-0.1)) + (-0.1); //value -0.1-->0.1
    var y = Math.random() * 0.1; //value 0-->0.1
    var z = Math.random() * (0.1 - (-0.1)) + (-0.1); //value -0.1-->0.1
    vec3.set(particle.velocity, x, y, z);
    this.particles.push(particle);
}

Upvotes: 0

Views: 58

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075467

At the moment, you have only one object that you're repeatedly putting in the array: this.model. This line:

var particle = this.model;

doesn't copy this.model, it just uses a new variable to refer to it. Then each time you do

particle.velocity = vec3.create();

...you overwrite the previous loop's value on particle.velocity, which is also this.model.velocity, because particle === this.model.

It sounds like you want to copy this.model, rather than reusing it. How you do that will depend a lot on this.model. Here's a naive way:

function shallowCopy(source) {
    var key, dest = {};
    for (key in source) {
        dest[key] = source[key];
    }
    return dest;
}

then

var particle = shallowCopy(this.model);

...but again, it depends a lot on what this.model is. If this.model has properties that refer to other objects, the above reuses those objects; you'd need a "deep" cloning function to make copies of those.

It's likely what you really want, rather than cloning, is a constructor function:

function Model() {
    // Set up basic properties and such on `this`, e.g.
    this.foo = "bar";
}

then

var particle = new Model();

Upvotes: 2

Related Questions