xxxxxxxxxx
81
/*
Adapted from Daniel Shiffman's textbreakingup
http://learningprocessing.com/examples/chp17/example-17-06-textbreakingup
*/
let word = "Interactive";
// create an array to store the characters
let letters = [];
function setup() {
createCanvas(400, 400);
textSize(48);
// first position to draw first letter
let x = 100;
// for all the letters in the word
// create a new Letter object
// increase x by the width of the character
// to draw the next letter after it
for (let i = 0; i < word.length; i++) {
let letter = new Letter(word[i], x, height / 2);
letters.push(letter);
x += textWidth(word[i]);
// console.log(x)
}
console.log(letters);
}
function draw() {
background(220);
// Loop through all letter objects
// to show and move them
// One way
for (let letter of letters) {
letter.display();
letter.dance();
if (mouseIsPressed) letter.home();
}
// Another way
// for (let i = 0; i < letters.length; i++) {
// letters[i].display();
// letters[i].dance();
// if (mouseIsPressed) letters[i].home();
// }
}
class Letter {
constructor(letter, x, y) {
this.letter = letter;
this.x = x;
this.y = y;
this.homeX = x;
this.homeY = y;
}
display() {
fill(0);
text(this.letter, this.x, this.y);
}
// Move the letter randomly
dance() {
this.x += random(-2, 2);
this.y += random(-2, 2);
}
// At any point, the current location
// can be set back to the home location
// by calling the home() method on the object
home() {
this.x = this.homeX;
this.y = this.homeY;
}
}