If you're seeing this message, it means we're having trouble loading external resources on our website.

Si estás detrás de un filtro de páginas web, por favor asegúrate de que los dominios *.kastatic.org y *.kasandbox.org estén desbloqueados.

Contenido principal

Sistemas de sistemas de partículas

Revisemos por un momento en dónde estamos. Sabemos cómo hablar acerca de un objeto individual Particle. También sabemos cómo hablar de un sistema de objetos Particle, y a esto lo llamamos un “sistema de partículas”. Y definimos un sistema de partículas como una colección de objetos independientes. ¿Pero un sistema de partículas no es en sí mismo un objeto? Si ese es el caso (que lo es), no hay ninguna razón por la cual no podríamos tener también una colección de sistemas de muchas partículas, es decir, un sistema de sistemas.
Por supuesto que esta línea de pensamiento nos podría llevar aún más lejos, y tal vez te encierres en un sótano durante días haciendo un esbozo de un diagrama de un sistema de sistemas de sistemas de sistemas de sistemas de sistemas. De sistemas. Después de todo, así es como funciona el mundo. Un órgano es un sistema de células, un cuerpo humano es un sistema de órganos, un vecindario es un sistema de cuerpos humanos, una ciudad es un sistema de vecindarios, y así sucesivamente. Mientras que este es un camino interesante para recorrer, está más allá de donde tenemos que estar en este momento. No obstante, es muy útil saber cómo escribir un programa que lleve un registro de muchos sistemas de partículas, cada uno de los cuales lleva un registro de muchas partículas. Tomemos el siguiente escenario:
  • Empiezas con una pantalla en blanco.
  • Haces clic con el ratón y generas un sistema de partículas en la posición del ratón.
  • Cada vez que haces clic en el ratón, se crea un nuevo sistema de partículas en la posición del ratón.
Pruébalo tú mismo:
¿Cómo podríamos lograr esto en código? En el artículo anterior, almacenamos una sola referencia a un objeto ParticleSystem en la variable ps.
var ps = new ParticleSystem(new PVector(width/2, 50));

draw = function() {
  background(50, 50, 50);
  ps.addParticle();
  ps.run();
};
Ahora que tenemos múltiples sistemas, un número potencialmente siempre creciente, no queremos almacenarlos en variables individuales. En su lugar, vamos a utilizar un arreglo para llevar el registro de todos los sistemas. Vamos a iniciarlo vacío cuando se inicie el programa:
var systems = [];
Cada vez que se presione el ratón, se crea un nuevo objeto ParticleSystem y se agrega al arreglo:
mousePressed = function() {
  systems.push(new ParticleSystem(new PVector(mouseX, mouseY)));
};
Y en draw(), en lugar de hacer referencia a un solo objeto ParticleSystem, ahora vemos a todos los sistemas del arreglo y llamamos run() sobre cada uno de ellos.
draw = function() {
  background(50, 50, 50);
  for(var i = 0; i < systems.length; i++){
    systems[i].addParticle();
    systems[i].run();
  }
};
Ahora, pruébalo otra vez, con el código que escribimos:

¿Quieres unirte a la conversación?

  • Avatar starky tree style para el usuario Batista Oliver Henriquez
    angleMode = "radians";

    var Particle = function(position) {
    this.acceleration = new PVector(0, -0.05);
    this.velocity = new PVector(random(-1, 1), random(-1, 0));
    this.position = position.get();
    this.timeToLive = 100;
    };

    Particle.prototype.run = function() {
    this.update();
    this.display();
    };

    Particle.prototype.update = function(){
    this.velocity.add(this.acceleration);
    this.position.add(this.velocity);
    this.timeToLive -= 2;
    };

    Particle.prototype.display = function() {
    colorMode(HSB);
    noStroke();
    var color = constrain((100 - this.timeToLive)/2,0,40);
    fill(color, 255, 255, this.timeToLive);
    ellipse(this.position.x, this.position.y, 12, 12);
    };

    Particle.prototype.isDead = function() {
    if (this.timeToLive < 0) {
    return true;
    } else {
    return false;
    }
    };

    var ParticleSystem = function(position) {
    this.origin = position.get();
    this.particles = [];
    };

    ParticleSystem.prototype.addParticle = function() {
    this.particles.push(new Particle(this.origin));
    };

    ParticleSystem.prototype.run = function() {
    for (var i = this.particles.length-1; i >= 0; i--) {
    var p = this.particles[i];
    p.run();
    if (p.isDead()) {
    this.particles.splice(i, 1);
    }
    }
    };

    // We start off with an empty systems array
    var systems = [];

    // We fill up the leaves array with positions
    var leaves = [];
    for (var i = 0; i < 100; i++) {
    leaves.push(new PVector(random(0, width), random(0, height)));
    }

    mouseClicked = function() {
    systems.push(new ParticleSystem(new PVector(width/2, height/2)));
    };

    mouseDragged = function() {
    systems.push(new ParticleSystem(new PVector(mouseX, mouseY)));
    };

    draw = function() {
    colorMode(RGB);
    background(66, 57, 11);

    for (var i = 0; i < leaves.length; i++) {
    image(getImage("avatars/leaf-orange"), leaves[i].x, leaves[i].y, 30, 30);
    }
    for (var i = 0; i < systems.length; i++){
    systems[i].addParticle();
    systems[i].run();
    }
    };
    (4 votos)
    Avatar Default Khan Academy avatar para el usuario
¿Sabes inglés? Haz clic aquí para ver más discusiones en el sitio en inglés de Khan Academy.