0

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);
}
4
  • 2
    What is this.model? Commented Mar 4, 2014 at 10:04
  • Can you show the vec3 code? Commented Mar 4, 2014 at 10:04
  • You need to copy the objects. You may look for "deep cloning" or simply implement a specific cloning. Commented Mar 4, 2014 at 10:04
  • create a new particle on each iteration Commented Mar 4, 2014 at 10:07

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

A constructor definitely sounds like the requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.