David J. - 7 months ago 55

Javascript Question

Apparently I need to practice more trig. I'm trying to position a number of circles equal to

`categories.length`

`var categoryX, categoryY;`

for (var j=0; j<categories.length; j++){

categoryX = width/2 + (250*cos(frameCount/3000) * cos(j*PI/categories.length));

categoryY = height/2 + (250*sin(frameCount/3000) * cos(j*PI/categories.length));

ellipse(categoryX, categoryY, 250, 250);

The circles should move with time (hence the frameCount) but also start along different radians of a circle. This code doesn't work.

Can anyone tell me why?

Answer

You should not multiply the (co)sines. Instead, add their arguments together for use in one (co)sine. I also think you want to mutiply *j* with 2π, instead of π, so you cover the whole arc around the central point:

```
cos(frameCount/3000 + j*2*PI/categories.length)
```

Same for the sine.

So the code would become:

```
var categoryX, categoryY;
for (var j=0; j<categories.length; j++){
categoryX = width/2 + 250*cos(frameCount/3000 + j*2*PI/categories.length);
categoryY = height/2 + 250*sin(frameCount/3000 + j*2*PI/categories.length);
ellipse(categoryX, categoryY, 250, 250);
// ...
}
```

Source (Stackoverflow)