Не могу правильно превратить этот набор функций в рабочий класс (p5.js) - PullRequest
0 голосов
/ 07 января 2019

Я превращаю набор функций, которые создают дерево в класс, однако, когда функции создают большое разветвленное дерево, версия класса не правильно рисует дерево, как это происходит в функции. У меня нет большого опыта работы с javascript и oop, поэтому обнаружение проблемы здесь очень расстраивает и затрудняет меня, я был бы признателен, если бы кто-то мог указать, что мне нужно изменить в классе, чтобы он отображался правильно.

Я сравнивал код рядом, пытаясь выяснить, есть ли какие-либо различия, но я чувствую, что проблема связана с различиями в функциях и методах внутри класса, из-за чего мне очень трудно определить, чтобы определить.

Код, который я пытаюсь исправить, можно найти здесь: https://editor.p5js.org/remcqueen/sketches/S1ETz7WfV

Ожидаемый результат кода совпадает с версией функции, которую можно найти здесь: https://editor.p5js.org/remcqueen/sketches/B1HdvWbzN

Должно быть сформировано полное безлистное дерево. однако то, что в настоящее время показано, совсем другое.

Буду признателен всем, кто взглянет на эту проблему, чтобы помочь решить ее.

Вот класс, который я пытаюсь исправить:

class createTree {

  constructor() {
    this.tree = createGraphics(width-10, height-10);
    this.n = 0;
  }

  draw() {
    this.tree.beginShape();
    this.tree.noStroke();
    this.tree.background(0,0);
    for (this.i = 0; this.i < 3; this.i++) {
        this.tree.fill(map(this.i, 0, 2, 60, 20));
        this.branch(width/2, height, 70, -HALF_PI, 150, 0);
    }
    this.tree.endShape();
    image(this.tree, 5, 5);
  }


  branch(x, y, bSize, theta, bLength, pos) {
    this.x = x;
    this.y = y;
    this.bSize = bSize;
    this.theta = theta;
    this.bLength = bLength;
    this.pos = pos;
    this.n += 0.01;
    this.diam = lerp(this.bSize, 0.7 * this.bSize, this.pos / this.bLength);
    this.diam *= map(noise(this.n), 0, 1, 0.4, 1.6);

    this.tree.ellipse(this.x, this.y, this.diam, this.diam);
    if (this.bSize > 0.6) {
        if (this.pos < this.bLength) {
            this.x += cos(this.theta + random(-PI / 10, PI / 10));
            this.y += sin(this.theta + random(-PI / 10, PI / 10));
            this.branch(this.x, this.y, this.bSize, this.theta, this.bLength, this.pos + 1);
        } else {
            this.drawLeftBranch = random(1) > 0.1;
            this.drawRightBranch = random(1) > 0.1;
            if (this.drawLeftBranch) this.branch(this.x, this.y, random(0.5, 0.7) * this.bSize, this.theta - random(PI / 15, PI / 5), random(0.6, 0.8) * this.bLength, 0);
            if (this.drawRightBranch) this.branch(this.x, this.y, random(0.5, 0.7) * this.bSize, this.theta + random(PI / 15, PI / 5), random(0.6, 0.8) * this.bLength, 0);

            if (!this.drawLeftBranch && !this.drawRightBranch) {
                this.tree.push()
                this.tree.translate(this.x, this.y);
                this.tree.rotate(this.theta);
                this.tree.quad(0, -this.diam / 2, 2 * this.diam, -this.diam / 6, 2 * this.diam, this.diam / 6, 0, this.diam / 2);
                this.tree.pop();
            }
        }
    }
  }
}

1 Ответ

0 голосов
/ 07 января 2019

Вы устанавливаете переменные экземпляра повсюду, где то, что вы действительно хотите, это переменные, локальные для функции. Когда вы устанавливаете переменные в экземпляре, они совместно используются во время рекурсии, а это не то, что вам нужно. Например, вам нужно, чтобы все параметры функции были локальными для функции:

Добавление их в this разрушает все:

branch(x, y, bSize, theta, bLength, pos) {
   this.x = x;  // <-- don't do that
   this.y = y;
 // etc
}

Вот очищенный фрагмент:

var a;
function setup() {
  createCanvas(900, 700);
  colorMode(HSB);
  noLoop();
  noStroke();
  a = new createTree();
  a.draw();
}

class createTree {

  constructor() {
    this.tree = createGraphics(width, height);
    this.n = 0;
  }

  draw() {
    this.tree.beginShape();
    this.tree.noStroke();
    this.tree.background(0,0);
		
    for (let i = 0; i < 3; i++) {
        this.tree.fill(map(i, 0, 2, 60, 20));
        this.branch(width/2, height, 70, -HALF_PI, 150, 0);
    }
    this.tree.endShape();
    image(this.tree, 5, 5);
  }


  branch(x, y, bSize, theta, bLength, pos) {
    
    this.n += 0.01;
    let diam = lerp(bSize, 0.7 * bSize, pos / bLength);
    diam *= map(noise(this.n), 0, 1, 0.4, 1.6);

    this.tree.ellipse(x, y, diam, diam);
    if (bSize > 0.6) {
        if (pos < bLength) {
            x += cos(theta + random(-PI / 10, PI / 10));
            y += sin(theta + random(-PI / 10, PI / 10));
            this.branch( x, y, bSize, theta, bLength, pos + 1);
        } else {
            let drawLeftBranch = random(1) > 0.1;
            let drawRightBranch = random(1) > 0.1;
            if (drawLeftBranch) this.branch(x, y, random(0.5, 0.7) * bSize, theta - random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);
            if (drawRightBranch) this.branch(x, y, random(0.5, 0.7) * bSize, theta + random(PI / 15, PI / 5), random(0.6, 0.8) * bLength, 0);

            if (!drawLeftBranch && !drawRightBranch) {
                this.tree.push()
                this.tree.translate(x, y);
                this.tree.rotate(theta);
                this.tree.quad(0, -diam / 2, 2 * diam, -diam / 6, 2 * diam, diam / 6, 0, diam / 2);
                this.tree.pop();
            }
        }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
...