2018/05/14

Generative Art: Array de objetos v0.01



Código html (index.html):
<!doctype html>
<html>
  <head>
    <title>Array de objetos en p5.js</title>
    <script src="libraries/p5.js"></script>
    <script src="code.js"></script>
    <script src="Asteroide.js"></script>
</head>
  <body style="text-align:center; margin:0px">
  </body>
</html>

Código p5.js (code.js):
var asteroides = [];

function setup(){
  createCanvas(500,500);
  for (var i = 0; i < 100; i++) {
    asteroides.push(new Asteroide());
  }
}

function draw(){
  background(255,215,0);
  translate(width/2, height/2);
  for (var i = 0; i < asteroides.length; i++) {
    asteroides[i].dibujar();
    asteroides[i].mover();
  }
}

Código p5.js (Objeto Asteroide.js):
function Asteroide () {
  this.x;
  this.y;
  this.z = random(width);

  this.dibujar = function() {
    fill(0);
    noStroke();
    this.ax = map(this.x / this.z, 0, 1, 0, width);
    this.ay = map(this.y / this.z, 0, 1, 0, height);
    this.r = map(this.z, 0, width, 25, 0);
    rect(this.ax-this.r/2, this.ay-this.r/2, this.r, this.r);
  }

  this.mover = function() {
    this.z = this.z - 10;
    if (this.z < 1) {
      this.x = random(-width/4, width/4);
      this.y = random(-height/4, height/4);
      this.z = width;
    }
  }
}