Need help with trigonometry or circle geometry

Hello!

For a little project, I would like to put rectangles around a circle… with a twist : the length of the rectangle, the space between each rectangle, and the circle diameter, are user parameters, they must not be calculated or modified by code. So there will be a maximum of full rectangles around the circle, and the last rectangle will be shorter, to fill the gap. No problem with this part.

My problem is that I would like the rectangles to be placed so that the outside corners of all rectangles are exactly on the circle (see the pictures below). I have no idea how to do that programmatically, without using hardcoded values. It must work for any circle diameter and any rectangle length.

Here is my code, you can try it, just change “showTheExpectedResult” to true, to see the result that I’m expecting

let showTheExpectedResult = false;
let hardcodedCircleOffset = 22;
let hardcodedRectOffset = 6;
let circleDiameter = 500;
let rectLength = 150;
let rectWidth = 50;
let rectSpacing = -3;


function setup()
{
  createCanvas( 600, 600 );
  background( 200 );
  rectMode( CENTER );
  angleMode( DEGREES );
  translate( width / 2, height / 2 );
  
  
  // Draw circle
  fill( 255, 255, 0 );
  circle( 0, 0, circleDiameter + ( showTheExpectedResult ? hardcodedCircleOffset : 0 ) );
  
  
  // Draw full rectangles
  fill( 0, 255, 0, 128 );
  let numRect = PI * circleDiameter / ( rectLength + rectSpacing );
  let numRectFloored = floor( numRect );
  let rotation = 360 / numRect;
  let radius = ( circleDiameter - rectWidth ) / 2;
  
  for ( let i = 0; i < numRectFloored; i++ )
  {
    let angle = i * rotation;
    push();
    translate( radius * cos( angle ), radius * sin( angle ) );
    rotate( angle );
    rect( 0, 0, rectWidth, rectLength );
    pop();
  }
  
  
  // Draw last rectangle to fill the gap
  radius += showTheExpectedResult ? hardcodedRectOffset : 0;
  let angle = ( numRectFloored - 1 ) * rotation / 2 - 180;
  translate( radius * cos( angle ), radius * sin( angle ) );
  rotate( angle );
  rect( 0, 0, rectWidth, rectLength * ( numRect - numRectFloored ) );
}

This is the result of this code (note the smaller rectangle in the upper right):

And what I would like to do, without hardcoding anything:

I hope someone will be able to help ! Thanks in advance :slight_smile: