4. 모듈화: 객체, 배열 및 클래스
스케치가 복잡해짐에 따라 여러 유사한 요소를 효율적으로 관리하는 방법이 필요합니다. 객체, 배열 및 클래스는 이를 위한 강력한 도구를 제공합니다.
4.1. 데이터를 그룹화하는 객체 사용
객체는 "공"과 같은 단일 엔터티에 대한 관련 데이터(속성)와 동작(메서드)을 저장할 수 있습니다.
let ball = {
x: 100,
y: 100,
diameter: 50,
speedX: 3,
speedY: 2,
display: function() {
ellipse(this.x, this.y, this.diameter, this.diameter);
},
move: function() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x > width - this.diameter/2 || this.x < this.diameter/2) {
this.speedX *= -1;
}
if (this.y > height - this.diameter/2 || this.y < this.diameter/2) {
this.speedY *= -1;
}
}
};
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ball.move();
ball.display();
}
4.2. 배열로 여러 객체 관리
여러 개의 "공"을 가지려면 배열에 저장하고 배열을 반복하여 각 공을 업데이트하고 표시합니다.
let balls = [];
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
balls.push(new Ball(random(width), random(height), random(20, 50)));
}
}
function draw() {
background(220);
for (let i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].display();
}
}
// 4.3절에서 Ball 클래스 정의를 참조하세요.
4.3. 사용자 정의 클래스 생성
클래스는 객체를 만들기 위한 청사진입니다. 재사용 가능한 객체 유형을 정의하는 데 이상적입니다.
class Ball {
constructor(x, y, diameter) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
this.color = color(random(255), random(255), random(255));
}
move() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x > width - this.diameter/2 || this.x < this.diameter/2) {
this.speedX *= -1;
}
if (this.y > height - this.diameter/2 || this.y < this.diameter/2) {
this.speedY *= -1;
}
}
display() {
fill(this.color);
noStroke();
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
// 이 Ball 클래스는 위 배열 예제와 함께 사용됩니다.