David J. David J. - 10 days ago 6
Javascript Question

why aren't these ellipses being placed correctly?

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

categories.length
around a central axis. Here's the code I'm using (p5.js):

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);
    // ...
}
Comments