Why can't I draw both figures when the line moves? How to use if/else vs switch statement

int v=1,a = 0,r=50;
void setup(){
  frameRate= 30;
void draw() {
  a = (a + 1) % height;  // 'a' increases between 0 and width 
  line(0, a, width, a);
  strokeWeight (2);
    case 1://As long as the line is in the top half of the window, a red circle is drawn in the
           //center of the window.
    if (a>height/2-r/2){
    case 2: //When the line is situated in the bottom half of the window
            //  a rectangle is drawn in the center of the window.
   if  (a>height/2+r/2){


Hi @add,

I think your issue is all about code structure and to figure out what is really needed and what not.
To not get too much in details and talk about your code in length, I’ll try to show by example …
Try to compare my code with yours and why I made it this way …

— mnse

int currentY=0; // keep current y value for the line
int r=50; // radius for the circle and size if rectangle

void setup(){
  // let's define rectangles by centerpoint and size
  // let's define ellipses by center and radius

void draw() {
  background(200); // clear backgound
  // no strokes for circle and rectangle
  // if the line is in upper half
  if (currentY<height/2) {
    // draw a red circle
  } else { // else not in upper must be lower
    // draw a green rect
  // draw the line in front of the shapes above
  stroke(0); // black 
  strokeWeight(2); // a bit thicker 
  line(0, currentY, width, currentY);
  // update the y value to move down and start over on bottom
  currentY = (currentY + 1) % height; 

Hello @add :slightly_smiling_face:

You are mixing your use of conditionals together here. Use either if/else ~OR~ switch.
However, If you really want to use the switch statement then you could set it up this way:

int num = 0;
  if (y >= height/2)
    num = 1;

  switch(num) {
  case 0:
    fill(255, 0, 0);
    circle(width/2, height/2, r);
  case 1: //When the line is situated in the bottom half of the window
    fill(0, 255, 0);
    rect(width/2, height/2, r, r);

But @mnse 's solution is cleaner IMHO.
Take a look at the reference to read about switch statements here:

Also, I hope you don’t mind but I changed the title of your post to include relevant keywords for others who may search for the same information in the future. Of course, please edit if you do not feel this accurately reflects your question! :slightly_smiling_face:

1 Like