绘制具有相同变量的多个类



我想我对类和封装的理解不够好,因为当我画垂直的时候与横向类同时,它们相互影响,并改变它们的绘画方式。但当我一次画一个类时,它就像一个意图。我不明白为什么会这样,因为它们是两个独立的类,其中包含的变量不应该在外面访问?

let spacing = 50;
let xx = 0;
let yy = 0;
function setup() {
createCanvas(1500, 1500);
background(0);
}
function draw() {
let hori = new Horizontal()
let vert = new Vertical()

hori.drawit();
vert.drawit();
}
class Vertical{
constructor(){
}

drawit(){
if (random(1) < 0.5) {
fill(55, 24, 25)
stroke(155);
rect(yy+random(15),xx+random(20), random(10), random(100));
} else {
rect(yy,xx, random(20), random(10));
}
xx = xx + spacing;
if (xx > width) {
xx = 0;
yy = yy + spacing;
}
}
}
class Horizontal{
constructor(){
}
drawit(){
if (random(1) < 0.5) {
fill(55, 24, 25)
stroke(155);
rect(yy+random(15),xx+random(20), random(10), random(100));
//line(xx, yy, xx + spacing, yy + spacing);
} else {
rect(yy,xx, random(20), random(10));
}
yy = yy + spacing;
if (yy > width) {
yy = 0;
xx = xx + spacing;
}
}

}

@ggorlen的评论给了你一些很好的建议。下面是它在代码中的样子:

封装的思想意味着你的类不应该改变类外的任何变量。您的VerticalHorizontal类都修改了相同的全局变量xxyy。这就是他们互相干扰的原因。我这样做是为了让它们每个都有自己的坐标this.xthis.y

在p5.js的draw()函数中调用new Horizontal()意味着你在每个动画帧上得到一个Horizontal类的新实例。但是我们希望我们的类知道它们最后使用的位置。所以我在setup()函数中创建了一个Horizontal实例和一个Vertical实例。它们都从(0,0)开始,在每个动画帧上垂直或水平移动50px。

const spacing = 50;
let hori;
let vert;
function setup() {
createCanvas(1500, 1500);
background(0);
hori = new Horizontal(0, 0);
vert = new Vertical(0, 0);
}
function draw() {
fill(55, 24, 25);
stroke(155);
hori.drawit();
vert.drawit();
}
class Vertical {
constructor(x, y) {
this.x = x;
this.y = y;
}
drawit() {
if (random(1) < 0.5) {
rect(this.x + random(15), this.y + random(20), random(10), random(100));
} else {
rect(this.x, this.y, random(20), random(10));
}
this.y = this.y + spacing;
if (this.y > height) {
this.y = 0;
this.x = this.x + spacing;
}
if (this.x > width) {
this.x = 0;
}
}
}
class Horizontal {
constructor(x, y) {
this.x = x;
this.y = y;
}
drawit() {
if (random(1) < 0.5) {
rect(this.x + random(15), this.y + random(20), random(10), random(100));
} else {
rect(this.x, this.y, random(20), random(10));
}
this.x = this.x + spacing;
if (this.x > width) {
this.x = 0;
this.y = this.y + spacing;
}
if (this.y > height) {
this.y = 0;
}
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.js"></script>

最新更新