`targetX`

and `targetY`

are global variables. It means that you can access and modify them no matter where you are in your program so it includes functions.

The first thing you do in your draw() loop is a call to `reachSegment`

:

```
reachSegment(0, mouseX, mouseY);
```

0 correspond to the last segment and `mouseX`

, `mouseY`

is the position that you are trying to reach.

The function goes like this:

```
void reachSegment(int i, float xin, float yin) {
float dx = xin - x[i]; // x delta between the segment and the target x position
float dy = yin - y[i]; // y delta between the segment and the target y position
angle[i] = atan2(dy, dx); // The new angle of the segment
targetX = xin - cos(angle[i]) * segLength; // The new target x position for the next segment
targetY = yin - sin(angle[i]) * segLength; // The new target y position for the next segement
}
```

The key thing to realize here is that you are updating the `targetX`

and `targetY`

values.

And the way you do that is by computing the new base position of the current segment. So the position of the base point of the current segment is stored in `targetX`

and `targetY`

.

Then you go back in your draw loop for this:

```
for(int i=1; i<numSegments; i++) {
reachSegment(i, targetX, targetY);
}
```

Here you are looping through the remaining segments (you already have done the first one).

The difference is that now the target is not `mouseX`

and `mouseY`

anymore but `targetX`

and `targetY`

. And as we have seen, `targetX`

and `targetY`

are updated everytime you call the function so it correspond to the base of the previous segment.

So basically, the idea is to rotate the last segment to point toward the mouse, then compute where the base of that segment would be, store that position in `targetX`

and `targetY`

then do the same for the other segments using the base of the upper segment as a target.