ProcessingJS Create an Object which holds random number of items to draw flowers

164 views Asked by At

I am working on drawing a tulip flower in ProcessingJS. I have code as below. The code will draw a tulip flower with a petal, and x, y, height is the preference for pedal location and height.

`/*****************
*Tulip Object Type
******************/
var Tulip = function(x, y, height) {
    this.x = x;
    this.y = y;
    this.height = height;
};

Tulip.prototype.draw = function() {
    noStroke();
    fill(16, 122, 12);
    rect(this.x, this.y, 10, -this.height);
    fill(255, 0, 0);
    // petals
    ellipse(this.x+5, this.y-this.height, 44, 44);
    triangle(this.x-16, this.y-this.height,
            this.x+20, this.y-this.height,
            this.x-20, this.y-this.height-31);
    triangle(this.x-14, this.y-this.height,
            this.x+24, this.y-this.height,
            this.x+3, this.y-this.height-39);
    triangle(this.x+-4, this.y-this.height,
            this.x+26, this.y-this.height,
            this.x+29, this.y-this.height-36);
};
`

Function to draw:

void setup()
{
  size(400 , 400);
  background(125);
}

 var tulip = new Tulip (200, 200, 10);
 draw = function() {
    tulip.draw();

};

I want to draw random numbers of tulip flowers, with the value of x, y and height also randomly set respectively.

I'm thinking of using an array but after many tries still not working. How I create randomly flowers based on the Tulip object above?

2

There are 2 answers

0
ariel On BEST ANSWER

Create an array of random tulips:

int numTulips = random(10, 20); // between 10 and 20 tulips
Tulip[] tulips = new Tulip[numTulips];
for (int i = 0; i < numTulips; i++) {
  tulips[i] = new Tulip (random(30, 370), random(30, 370), random(10, 30));
}

Then draw the tulips

draw = function() {
   for (int i = 0; i < numTulips; i++) {
      tulips[i].draw();
    }
 };

Sample: https://codepen.io/bortao/pen/jOPobam

0
Valentine Heartilly On

Create an array of tulip. Use random to set length of that array. After that, loop throw the array and add tulip to array. Remember use random to make x, y & height of each tulip.

Now you have an array with random number of random tulip, you can do anything you want

Ex:

var Tulip = function(x, y, height) {
    this.x = x;
    this.y = y;
    this.height = height;
};

var totalTulip = Math.floor(Math.random() * 10) + 1; // from 1 to 10
var tuplips = [];

for (var i = 0; i < totalTulip; i++) {
    var x = Math.floor(Math.random() * 20) + 1; // from 1 to 20;
    var y = Math.floor(Math.random() * 20) + 1; // from 1 to 20;
    var h = Math.floor(Math.random() * 100) + 1; // from 1 to 100;

    var tuplip = new Tulip(x, y, h);

    tuplips.push(tuplip);
}

P/s: it's Javascript :D