Points refuse to move towards on a circle
in
Programming Questions
•
1 year ago
In attempting to follow a simple example from Programming.Architecture by Paul Coates, I stumbled on some bizarre emergent phenomenon.
The goal was to have randomly placed points converge upon a circle define by a position and a radius. My code ended up producing the enigma in the above screenshot, (note I am not calling background()) where some points attach to the circle's boundary, and others move off into the distance. I suspect the sign of sin() and cos() values in the 4 quadrants has something to do with it?
My trig is fairly rusty, but there should be a simple fix.
Thanks in advance, and let me know if I can clarify something.
Here is my code:
The goal was to have randomly placed points converge upon a circle define by a position and a radius. My code ended up producing the enigma in the above screenshot, (note I am not calling background()) where some points attach to the circle's boundary, and others move off into the distance. I suspect the sign of sin() and cos() values in the 4 quadrants has something to do with it?
My trig is fairly rusty, but there should be a simple fix.
Thanks in advance, and let me know if I can clarify something.
Here is my code:
- PVector centerPt;
- float rad = 200;
- int numAgents = 500;
- Agent[] agents = new Agent[numAgents];
- void setup() {
- size(600, 800, P3D);
- centerPt = new PVector(width/2, height/2);
- for (int i = 0; i < numAgents; i++) agents[i] = new Agent();
- }
- void draw() {
- //translate(0, 0, -mouseX);
- for (Agent a : agents) {
- a.update();
- }
- }
- class Agent {
- PVector pos;
- Agent() {
- pos = new PVector(random(width), random(height));
- }
- void update() {
- float magnitude = dist(centerPt.x, centerPt.y, pos.x, pos.y);
- float sine = (centerPt.x - pos.x) / magnitude;
- float cosine = (centerPt.y - pos.y) / magnitude;
- if (dist(pos.x, pos.y, centerPt.x, centerPt.y) > rad) {
- pos.x += cosine * 1;
- pos.y += sine * 1;
- }
- else {
- pos.x += cosine * -1;
- pos.y += sine * -1;
- }
- point(pos.x, pos.y);
- }
- }
1