Skip to content

Example 08 01 singleobject constructor #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 27 additions & 22 deletions chp08_objects/example_08_01_singleobject/sketch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,41 @@

// Example 8-1: A Car class and a Car object

var car; // Declare car object as a global variable.
let car; // Declare car object as a global variable.

function setup() {
createCanvas(480, 270);
// Initialize Car object

car = {
c: color(175),
xpos: width/2,
ypos: height/2,
xspeed: 3,
display: function() { // Function.
// The car is just a square
rectMode(CENTER);
stroke(0);
fill(this.c);
rect(this.xpos,this.ypos,20,10);
},
move: function() { // Function.
this.xpos = this.xpos + this.xspeed;
if (this.xpos > width) {
this.xpos = 0;
}
}
};
car = new Car();
}

function draw() {
background(100);
// Operate Car object.
car.move(); // Operate the car object in draw( ) by calling object methods using the dots syntax.
car.move(); //
car.display();
}

class Car {
constructor(c, x, y, xspeed) {
this.c = color(175);
this.x = width/2;
this.y = height/2;
this.xspeed = 3;
}

display() {
// The car is just a square
rectMode(CENTER);
stroke(0);
fill(this.c);
rect(this.x, this.y, 20, 10);
}

move() {
this.x = this.x + this.xspeed;
if (this.x > width) {
this.x = 0;
}
}
}