使用参数显示 p5.js 中的一个点

Showing a point in p5.js using parameters

在我的 'show' 函数中我有这个命令: 点(this.position.x, this.position.y);

这不会导致点出现,请注意,我已尝试在调用此点 (..) 之前直接打印出这些值,它们存在并且在框架内。我也试过将它们解析为 int 并通过但没有成功。

但是:

请在下面找到我的代码,我不知道问题出在哪里

var firework;

function setup() {
    createCanvas(500, 400);
    stroke('purple');
    strokeWeight(10);
    firework = new Particle(random(width), height);
}

function draw() {
    background(51);
    firework.update();
    firework.show();
}

function Particle(x, y) {
    this.position = createVector(x, y);
    this.velocity = createVector(0, 0);
    this.acceleration = createVector(0, 0);

    this.applyForce = function(force) {
        this.acceleration.add(force);
    }

    this.update = function() {
        this.position.add(this.velocity);
        this.velocity.add(this.acceleration);
        this.acceleration.mult(0);
    };

    this.show = function() {
        point(this.position.x, this.position.y);
    };
}

实际上是在canvas上画,只是看起来不明显。这是因为您将它的 y 值设置为 height,这只会将它放在 canvas 的最底部。颜色也让人很难看清画点的位置。下图显示了在 (310,399) 绘制的点。


要解决此问题,请将 y 值更改为介于 0height 之间。实现此目的的一种方法是将 y 值随机化,就像您对 random(width)x 所做的那样。在我下面的解决方案中,我还更改了使用颜色值 151 而不是 51 绘制的背景以获得更好的对比度。

var firework;

function setup() {
  createCanvas(500, 400);
  stroke("purple");
  strokeWeight(10);
  firework = new Particle(random(width), random(height));
}

function draw() {
  background(151);
  firework.update();
  firework.show();
}

function Particle(x, y) {
  this.position = createVector(x, y);
  this.velocity = createVector(0, 0);
  this.acceleration = createVector(0, 0);

  this.applyForce = function(force) {
    this.acceleration.add(force);
  };

  this.update = function() {
    this.position.add(this.velocity);
    this.velocity.add(this.acceleration);
    this.acceleration.mult(0);
  };

  this.show = function() {
    point(this.position.x, this.position.y);
  };
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>