用p5js绘制一个20毫米的不断变化颜色的球在界面跳动并且会留下轨迹
以下是使用p5.js绘制一个20毫米的不断变化颜色的球,并且会留下轨迹的代码:
let xPos = 0;
let yPos = 0;
let xSpeed = 2;
let ySpeed = 2;
let trail = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// 更新球的位置
xPos += xSpeed;
yPos += ySpeed;
// 检查球是否碰到画布边缘
if (xPos <= 10 || xPos >= width - 10) {
xSpeed *= -1;
}
if (yPos <= 10 || yPos >= height - 10) {
ySpeed *= -1;
}
// 记录球的位置到轨迹数组中
trail.push({ x: xPos, y: yPos });
// 限制轨迹数组的长度,只保留最近的100个点
if (trail.length > 100) {
trail.shift();
}
// 绘制轨迹
for (let i = 0; i < trail.length; i++) {
let alpha = map(i, 0, trail.length - 1, 0, 255);
fill(0, 0, 255, alpha);
noStroke();
ellipse(trail[i].x, trail[i].y, 20, 20);
}
// 绘制球
fill(random(255), random(255), random(255));
stroke(0);
strokeWeight(2);
ellipse(xPos, yPos, 20, 20);
}
在上述代码中,我们使用xPos和yPos变量来跟踪球的位置,xSpeed和ySpeed变量用于控制球的速度。轨迹点被存储在一个数组trail中,并且每一帧都会将当前位置添加到数组中。
然后,我们遍历轨迹数组,并使用map()函数根据索引值来计算透明度,以实现渐变效果。最后,我们绘制球的位置以及轨迹点的位置。
你可以将以上代码复制到p5.js的在线编辑器(https://editor.p5js.org/)中运行,并通过点击运行按钮来查看效果。
原文地址: https://www.cveoy.top/t/topic/i4c9 著作权归作者所有。请勿转载和采集!