Processing
Magnet Field
A field of small needles, all listening for magnets. Move your pointer across and they lean in; click to drop a magnet that stays. The live example for the Processing guide.
مجوز: CC BY-NC-SA 4.0: ریمیکس با ذکر نام، غیرتجاری، با همین مجوز
دیدن کد
float t = 0;
float[] mx = new float[8];
float[] my = new float[8];
int magnets = 0;
void setup() {
size(600, 600);
strokeCap(ROUND);
}
void draw() {
background(16, 18, 24);
t += 0.02 * params.speed;
int step = (int) params.density;
float reach = params.reach;
for (int gx = step / 2; gx < width; gx += step) {
for (int gy = step / 2; gy < height; gy += step) {
float ax = 0;
float ay = -1;
float pull = 0;
float dx = mouseX - gx;
float dy = mouseY - gy;
float d = sqrt(dx * dx + dy * dy);
if (d < reach && d > 0.01) {
float w = 1 - d / reach;
ax += (dx / d) * w * 2.2;
ay += (dy / d) * w * 2.2;
pull = max(pull, w);
}
for (int i = 0; i < magnets; i++) {
float mdx = mx[i] - gx;
float mdy = my[i] - gy;
float md = sqrt(mdx * mdx + mdy * mdy);
if (md < reach * 0.8 && md > 0.01) {
float w = 1 - md / (reach * 0.8);
ax += (mdx / md) * w * 1.8;
ay += (mdy / md) * w * 1.8;
pull = max(pull, w * 0.9);
}
}
ax += cos(t + gx * 0.02 + gy * 0.013) * 0.35;
ay += sin(t * 1.3 + gx * 0.017) * 0.35;
float ang = atan2(ay, ax);
float len = step * 0.36;
float cx = gx + cos(ang) * len;
float cy = gy + sin(ang) * len;
float bx = gx - cos(ang) * len;
float by = gy - sin(ang) * len;
stroke(lerpColor(color(90, 100, 130), color(255, 180, 84), pull));
strokeWeight(2);
line(bx, by, cx, cy);
noStroke();
fill(lerpColor(color(120, 130, 160), color(255, 210, 140), pull));
ellipse(cx, cy, 4.5, 4.5);
}
}
for (int i = 0; i < magnets; i++) {
noStroke();
fill(255, 180, 84, 60);
ellipse(mx[i], my[i], 26 + 5 * sin(t * 3 + i), 26 + 5 * sin(t * 3 + i));
fill(255, 200, 120);
ellipse(mx[i], my[i], 9, 9);
}
}
void mousePressed() {
if (magnets < 8) {
mx[magnets] = mouseX;
my[magnets] = mouseY;
magnets++;
} else {
for (int i = 0; i < 7; i++) { mx[i] = mx[i + 1]; my[i] = my[i + 1]; }
mx[7] = mouseX;
my[7] = mouseY;
}
}