是否可以通过p5.js在多点场景中跟踪点的路径

问题描述 投票:0回答:1

我有一个场景,其中P0P4的几个点在画布上彼此独立移动了五秒钟。当我按下一个按钮时,它们都开始移动,五秒钟后它们都停止了;如果我再次按下该按钮,它们将再次开始移动。第一次按下按钮时,我只需要P0即可留下一条路径,第二次它应该删除最后一条路径并将其替换为新路径点。

我无法完成这项工作。我知道使该点偏离轨迹的唯一方法是从function draw的乞求中删除背景色,但这会使所有内容偏离轨迹。

javascript animation p5.js
1个回答
0
投票

一种简单的解决方案是通过存储坐标,然后绘制整个轨迹来跟踪路径。此代码段应说明其要点(单击画布上的以重置足迹图):

// Keep track of the path
let trail = []

function setup(){
  createCanvas(400, 180)
  noStroke()
}

function draw(){
  background(50)
  
  // Point with no trail
  fill('red')
  ellipse(mouseX-20, mouseY-20, 10)
  
  // Point with trail
  fill('blue')
  trail.push({x: mouseX, y: mouseY}) // Add latest position to the array
  for(let point of trail)
    ellipse(point.x, point.y, 10) // Draw a circle for each of the positions
  
  // Point with no trail
  fill('yellow')
  ellipse(mouseX+20, mouseY+20, 10)
}

function mouseClicked(){
  // reset the array so a new trail can be drawn
  trail = []
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.