Нужна помощь в получении функции рисования линии P5 - PullRequest
1 голос
/ 01 февраля 2020

Я пытаюсь повторить функцию соединения с сырой линией, которая у меня здесь работает, https://editor.p5js.org/knectar/sketches/0Thp1IJn, но с использованием объектов в массиве. Кажется, что этот код должен работать, но значения не заполняются так, как нужно для рисования соединительной линии. Любая помощь будет оценена!

Вот код (или здесь https://editor.p5js.org/knectar/sketches/HYPwtjge):

var dotCount = 2;
var dot;
var xTempPos, yTempPos;
var xEndPos, xEndPos; 

function setup() {
  createCanvas(windowWidth, windowHeight);

  noStroke();
  fill(200);
  for (let i = 0; i < dotCount; i++) {
    dotArray.push(new Dot());
  }
}

function draw() {
  // background(0);

  for (let i = 0; i < dotArray.length; i++) {
    dotArray[i].sketch();    
  }

  for (let i = dotArray.length - 1; i > 0; i--) {
    dotArray[i].connect();

    xEndPos = dotArray[i].xPos;
    xEndPos = dotArray[i].yPos;

    xTempPos = dotArray[i - 1].xPos;
    yTempPos = dotArray[i - 1].yPos;

    console.log(xTempPos);

  }
}

class Dot {

  constructor() {
    this.xStartPos = random(width);
    this.yStartPos = random(height);
    this.rad = 5;
  }

  sketch() {
    ellipse(this.xStartPos, this.yStartPos, this.rad);
  }

  connect() {
    stroke(200);
    strokeWeight(1);

    line(this.xStartPos, this.yStartPos, xTempPos, yTempPos);

    if (xTempPos <= xEndPos) {
      xTempPos = xTempPos + 1;
    }

    if (yTempPos <= xEndPos) {
      yTempPos = yTempPos + 1;
    }

  }

}```

1 Ответ

1 голос
/ 01 февраля 2020

Отсутствует объявление dotArray.

var dotArray = [];

Кроме того, оно должно быть xStartPos, yStartPos, а не xPos, yPos.

См. пример:

var dotCount = 2;
var dot;
var xTempPos, yTempPos;
var xEndPos, xEndPos; 
var dotArray = [];

function setup() {
  //createCanvas(windowWidth, windowHeight);
  createCanvas(400, 200);

  for (let i = 0; i < dotCount; i++) {
    dotArray.push(new Dot());
  }
}

function draw() {
  background(255, 255, 255);

  fill(255, 0, 0);
  stroke(255, 0, 0);
  strokeWeight(1);

  for (let i = 0; i < dotArray.length; i++) {
    dotArray[i].sketch();    
  }

  for (let i = dotArray.length - 1; i > 0; i--) {
    dotArray[i].connect();

    xEndPos = dotArray[i].xStartPos;
    xEndPos = dotArray[i].yStartPos;

    xTempPos = dotArray[i - 1].xStartPos;
    yTempPos = dotArray[i - 1].yStartPos;

    console.log(xTempPos);

  }
}

class Dot {

  constructor() {
    this.xStartPos = random(width);
    this.yStartPos = random(height);
    this.rad = 5;
  }

  sketch() {
    ellipse(this.xStartPos, this.yStartPos, this.rad);
  }

  connect() {

    line(this.xStartPos, this.yStartPos, xTempPos, yTempPos);

    if (xTempPos <= xEndPos) {
      xTempPos = xTempPos + 1;
    }

    if (yTempPos <= xEndPos) {
      yTempPos = yTempPos + 1;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
...