Array question based on Reach3 example (newbie)
in
Programming Questions
•
3 years ago
I'm trying to get to the next step of doing things with arrays. Using the really excellent "Reach" examples, I'm trying to make the code work with an arbitrary number of arms, each following the ball (or pointer, or whatever)...
I've got a zillion arms going, that part's pretty easy. But they're all moving together. I'm having difficulty figuring out how to get each arm to do its own calculation for following the ball.
I've got a zillion arms going, that part's pretty easy. But they're all moving together. I'm having difficulty figuring out how to get each arm to do its own calculation for following the ball.
- /**
- * Reach 3.
- * Based on code from Keith Peters (www.bit-101.com)
- *
- * The arm follows the position of the ball by
- * calculating the angles with atan2().
- */
- int numSegments = 6;
- float armSpace = 25;
- float[][] armArray;
- float[] x = new float[numSegments];
- float[] y = new float[numSegments];
- float[] angle = new float[numSegments];
- float segLength = 15;
- float targetX, targetY;
- float numArms = 1;
- int rows = 2;
- float ballX = 50;
- float ballY = 50;
- int ballXDirection = 1;
- int ballYDirection = -1;
- void setup() {
- size(640, 200);
- smooth();
- strokeWeight(20.0);
- stroke(0, 100);
- noFill();
- }
- void draw() {
- float numArms = width/armSpace;
- background(226);
- strokeWeight(20);
- moveBall();
- for (int k=0;k<rows;k++) {
- for(int j=0;j<numArms;j++) {
- x[x.length-1] = 0; // Set base x-coordinate
- y[x.length-1] = height; // Set base y-coordinate
- reachSegment(j, 0, ballX, ballY);
- for(int i=1; i<numSegments; i++) {
- reachSegment(j, i, targetX, targetY);
- }
- for(int i=x.length-1; i>=1; i--) {
- positionSegment(i, i-1);
- }
- for(int i=0; i<x.length; i++) {
- segment(x[i], y[i], angle[i], (i+1)*2);
- }
- translate(armSpace, 0);
- }
- translate(numArms*(-26), -25);
- }
- }
- void positionSegment(int a, int b) {
- x[b] = x[a] + cos(angle[a]) * segLength;
- y[b] = y[a] + sin(angle[a]) * segLength;
- }
- void reachSegment(int num, int i, float xin, float yin) {
- pushMatrix();
- float dx = xin - x[i];
- float dy = yin - y[i];
- angle[i] = atan2(dy, dx);
- targetX = xin - cos(angle[i]) * segLength;
- targetY = yin - sin(angle[i]) * segLength;
- popMatrix();
- }
- void segment(float x, float y, float a, float sw) {
- strokeWeight(sw);
- pushMatrix();
- translate(x, y);
- rotate(a);
- line(0, 0, segLength, 0);
- popMatrix();
- }
- void moveBall() {
- ballX = ballX + 1.0 * ballXDirection;
- ballY = ballY + 0.8 * ballYDirection;
- if(ballX > width-25 || ballX < 25) {
- ballXDirection *= -1;
- }
- if(ballY > height-25 || ballY < 25) {
- ballYDirection *= -1;
- }
- ellipse(ballX, ballY, 30, 30);
- }
1