Week 06: Objects
Topics:
-
Object: Data (member variables), Behaviors (methods), constructor(s), accessors (getters), mutators (setters)
-
Defining and using objects.
-
Arrays: Declaring, initializing, using.
-
Arrays of objects
-
Particle systems
1. Resources:
2. Ball
/* Aline Normoyle
* 10/13/2020
* Demo with two bouncing balls
*/
Ball ball1 = new Ball(0, 0); // call the constructor
Ball ball2 = new Ball(250, 10);
void setup() {
size(1000,1000);
}
void draw() {
background(128);
ball1.update(width, height);
ball1.draw();
ball2.update(width, height);
ball2.draw();
}
/* Aline Normoyle
* 10/13/2020
* Ball class
*/
class Ball {
// Define class data
// Member variables
float mPosX = 250;
float mPosY = 0;
float mYSpeed = 10;
float mXSpeed = 8;
float mVelY = 0;
float mVelX = 0;
// Define class methods
// Constructor
Ball(float x, float y) {
mPosX = x;
mPosY = y;
mYSpeed = 10;
mXSpeed = 8;
mVelY = mXSpeed;
mVelX = mYSpeed;
}
void update(float w, float h) {
mPosY += mVelY;
mPosX += mVelX;
if (mPosY > h) {
mVelY = -mYSpeed;
}
else if (mPosY < 0) {
mVelY = mYSpeed;
}
if (mPosX < 0) {
mVelX = mXSpeed;
}
else if (mPosX > w) {
mVelX = -mXSpeed;
}
}
void draw() {
circle(mPosX, mPosY, 50);
}
}
3. Car
/* Aline Normoyle
* 10/13/2020
* Demo with two cars moving left to right
*/
Car car1 = new Car(0, 100);
Car car2 = new Car(0, 300);
void setup() {
size(500, 500);
rectMode(CENTER);
}
void draw() {
background(200);
car1.update();
car1.draw();
car2.update();
car2.draw();
}
/* Aline Normoyle
* 10/13/2020
* Definition of Car class
*/
class Car {
float mposX = 250;
float mposY = 250;
float mspeed = 2;
Car(int x, int y) {
mposX = x;
mposY = y;
}
void update() {
mposX+= mspeed;
}
void draw() {
fill(128);
rect(mposX, mposY, 100, 50);
fill(0);
ellipse(mposX-30, mposY-30, 30,20);
ellipse(mposX-30, mposY+30, 30,20);
ellipse(mposX+30, mposY-30, 30,20);
ellipse(mposX+30, mposY+30, 30,20);
}
}
4. Random greetings
void setup() {
String[] greetings = {"hi", "aloha", "ciao", "bonjour"};
int idx = floor(random(0, greetings.length));
greetings[0] = "hello";
for (int i = 0; i < greetings.length; i++) {
println(greetings[i]);
}
size(500,500);
textAlign(CENTER);
textSize(64);
text(greetings[idx], 250, 250);
}
5. An array of Car
int numCars = 25;
Car[] cars = new Car[numCars];
void setup() {
size(500, 500);
rectMode(CENTER);
for (int i = 0; i < 2; i++){
int x = floor(random(0, width));
int y = floor(random(0, height));
cars[i] = new Car(x, y);
}
}
void draw() {
background(200);
for (int i = 0; i < cars.length; i++) {
if (cars[i] != null) {
cars[i].update(width, height);
cars[i].draw();
}
}
}
where car is defined as
class Car {
float mposX = 250;
float mposY = 250;
float mspeed = 2;
Car(int x, int y) {
mposX = x;
mposY = y;
}
void update(int w, int h) {
mposX+= mspeed;
}
void draw() {
fill(128);
rect(mposX, mposY, 100, 50);
fill(0);
ellipse(mposX-30, mposY-30, 30,20);
ellipse(mposX-30, mposY+30, 30,20);
ellipse(mposX+30, mposY-30, 30,20);
ellipse(mposX+30, mposY+30, 30,20);
}
}