我認為我對類和封裝的理解不夠好,因為當我同時繪制垂直和水平類時,它們會相互影響,并改變它們的繪制方式。但是當我一次畫一堂課時,它就像意圖一樣。我不明白為什么會這樣,因為它們是兩個單獨的類,并且它們中包含的變數不應該在外部訪問?
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;
}
}
}
uj5u.com熱心網友回復:
@ggorlen 的評論給了你一些非常好的建議。這是代碼中的樣子。
封裝的想法意味著你的類不應該改變類之外的任何變數。您Vertical和Horizontal類都在修改相同的全域變數xx和yy. 這就是他們互相干擾的原因。我這樣做是為了讓他們每個人都有自己的坐標this.x和this.y.
new Horizontal()在 p5.js 函式內部呼叫draw()意味著您會Horizontal在每個影片幀上獲得該類的新實體。但是我們希望我們的類知道他們最后使用的位置。所以我在函式中創建了一個Horizontal實體和一個Vertical實體setup()。(0,0)它們在每個影片幀上都從垂直或水平方向開始并移動 50 像素。
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/[email protected]/lib/p5.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/472797.html
標籤:javascript 哎呀 p5.js
上一篇:如何使用我的to_json_string方法將實體串列的JSON字串表示形式寫入檔案
下一篇:如何排列矩形?
