Objetos: ejemplo coche vertical
Car myCar1;
Car myCar2; // Two objects!
void setup() {
size(800,600);
// Parameters go inside the parentheses when the object is constructed.
myCar1 = new Car(color(255,0,0),500,400,-5);
myCar2 = new Car(color(0,0,255),300,300,5);
}
void draw() {
background(255);
myCar1.drive();
myCar1.display();
text(myCar1.ypos,400,200);
myCar2.drive();
myCar2.display();
}
// Even though there are multiple objects, we still only need one class.
// No matter how many cookies we make, only one cookie cutter is needed.
class Car {
color c;
float xpos;
float ypos;
float yspeed;
// The Constructor is defined with arguments.
Car(color tempC, float tempXpos, float tempYpos, float tempYspeed) {
c = tempC;
xpos = tempXpos;
ypos = tempYpos;
yspeed = tempYspeed;
}
void display() {
stroke(0);
fill(c);
rectMode(CENTER);
rect(xpos,ypos,20,10);
}
void drive() {
ypos = ypos + yspeed;
if (ypos > height && yspeed>0) {
ypos = 0;
}
ypos = ypos + yspeed;
if (ypos < 0 && yspeed<0) {
ypos = 600;
}
}
}
Comentarios
Publicar un comentario