Melting objects and array
in
Programming Questions
•
1 year ago
Hello,
I'm a really beginner and there is yet something I don't understand.
Based on the car's example of
the tutorial on objects, I try to make appear "lots of" cars in the window, but without declaring each of them individually. I would like to do this with an array and only one car appear.
So, what's wrong?
Here is my code.
- int nbreCar = 10;
- Car[] myCar;
- void setup(){
- background(0);
- size (200,200);
- smooth();
- // Variable value for each car (randomly assigned)
- // Détermination des valeurs de variables de chaque voiture (random)
- color c = color(random(125,255),random(125,255),random(125,255));
- float x = random (width);
- float y = (height/15)*random(height/15);
- float v = random(4.0);
- // Car declaring
- // Déclaration de la voiture
- myCar = new Car[nbreCar];
- // Assign of each car object as an object of Car class
- // Détermination de chaque voiture comme étant un objet de la classe Car
- for (int i =0; i < nbreCar; i++){
- myCar[i] = new Car(color(c), x, y, v);
- }
- }
- // Motor movement/display
- // Moteur déplacement / affichage
- void draw(){
- background(0);
- for (int i = 0; i < nbreCar; i++){
- myCar[i].drive();
- myCar[i].display();
- }
- }
- // Car object
- // Définition de l'objet voiture
- class Car {
- // Variables of a car
- // Déclaration des variables types de la voiture
- color c;
- float x, y, v ;
- // Constructor of a car
- // Constructor de la voiture
- Car(color tempC,float tempX, float tempY,float tempV){
- c = tempC;
- x = tempX;
- y = tempY;
- v = tempV;
- }
- // Car movement
- // Déplacement de la voiture
- void drive(){
- x = x + v;
- if (x > width) {
- x = 0;
- y += 15;
- }
- if (y > height) {
- y = 0;
- }
- }
- // Car displaying
- // Affichage de la voiture
- void display(){
- stroke (0);
- fill(c);
- ellipseMode(CENTER);
- ellipse (x-4,y-4,6,6);
- ellipse (x+4,y+4,6,6);
- ellipse (x+4,y-4,6,6);
- ellipse (x-4,y+4,6,6);
- rectMode(CENTER);
- rect(x,y,16,8);
- }
- }
1