【问题标题】:Rotate each trail particle at its center: p5.js在其中心旋转每个轨迹粒子:p5.js
【发布时间】:2022-01-06 23:20:24
【问题描述】:

我正在制作一个小动画,其中主广场不断旋转。现在我想给它添加一条线索,所以我在网上搜索并观看了Coding Train 的视频。然后我尝试旋转粒子,但是当我尝试这个时,一切看起来都很糟糕。我知道您可以使用 rotate() 函数在 p5 中旋转事物,但首先您必须使用 translate(),这会破坏一切。

我已经使用了这些功能,但正如我之前提到的那样,一切都会中断。我想问你是否有任何其他方法可以使这些粒子在它们的中心旋转,这不会破坏一切。

这是我的代码:

function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 255);
  document.oncontextmenu = function() {
    return false;
  }

}

let a = 0;
let hue = 0;
let w = 100;
let h = 100;
let history = [];

function draw() {
background(36);


let v = createVector(mouseX, mouseY);


history.push(v);

if (history.length > 100) {
  history.splice(0, 1);
}


push()
noStroke()
for (let i = 0; i < history.length; i++) {
  // THE ROTATION SHOULD BE HERE:


  let pos = history[i];
  fill((hue + i), 255, 255)
  rect(pos.x - w / 2, pos.y - h / 2, i, i)
}
pop()

push()
noStroke();
translate(mouseX, mouseY);
rotate(a);
fill(hue, 255, 255)
rect(0 - w / 2, 0 - h / 2, w, h);
pop()
a += 1 / 120;
hue += 1 / 5;

if (hue >= 255) {
  hue = 0;
}

}
html,
body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Sketch</title>

  <link rel="stylesheet" type="text/css" href="style.css">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.sound.min.js"></script>
</head>

<body>
  <script src="sketch.js"></script>
</body>

</html>

【问题讨论】:

    标签: javascript animation p5.js


    【解决方案1】:

    而不是将粒子绘制在您希望它们平移的位置。这允许将画布的 (0, 0) 坐标定位在 mouseX 和 mouseY 处。要将粒子居中在画布的 (0, 0) 处,只需将它们绘制在 -w/2-h/2 处。翻译和旋转它们后,一定要旋转它们并将它们翻译回原件。

      let pos = history[i];
      translate(pos.x, pos.y)
      rotate(a)
      fill((hue + i), 255, 255)
      rect(-w/2, -h/2, i, i)
      rotate(-a)
      translate(-pos.x , -pos.y)
    

    用上面的代码替换你的代码部分。

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2014-01-10
      相关资源
      最近更新 更多