Question about looping

Hi im having a doubt…
i know that draw is a endless loop, from beginning to las line of code…thats correct…

The doubt cames if i create a function inside draw…lets say MovePacman();
MovePacman have a loop for moving from coordX at 100 to an end point coordX at 300, step 1. So instead of moving directly from x 100 to x 300 ( like a jump), i want a smooth movement one by one pixel to the right ( x from 100 to 300, step 1)

So the draw loop is stopped till for finishes ? Or draw continues executing and “interceps” the for loop ? Like interrupts…

A sample of code because my english is not good:


let coordX=200;
let coordY=200;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  fill("yellow");
  circle(coordX, coordY, 50);
  movePacman(); //moving smoothly from coordX 200 to coordX 300
}

function movePacman()
{
while( coordX < 300)   
    {
      fill("yellow");
      coordX=coordX+0.001;
      circle(coordX,200, 50);
      console.log(coordX);
    }
}

Also the behaviour is weird…

How can i make a smooth transition, and how the draw loop interacts with movePacman while loop…

Thanks

Top level function movePacman() isn’t being “created” inside callback draw(), but it’s being “invoked” from draw().

When we invoke any other function inside a function, the function (the caller) invoking it awaits that invoked function (the callee) until it returns.

Therefore draw() will await movePacman()'s while loop fully.

For your movePacman() case, you already have variable coordX globally declared.
So you can increment that every time movePacman() is invoked:

"use strict";

var coordX = 200, coordY = 200;

function setup() {
  createCanvas(400, 400);
  fill("yellow").framerate(60);
}

function draw() {
  background(220).circle(coordX, coordY, 50);
  movePacman();
}

function movePacman() {
  if (coordX < 300) print("coordX:", coordX += .001);
  circle(coordX, 200, 50);
}

A similar online sketch demo:

But a much better solution would be to define a Pacman class instead:

4 Likes

Exactly.

draw() runs on and on but the screen is not updated throughout
but only once at the end of draw ().

Therefore you cannot make animations with while or for loops inside of draw().
(Since the screen is not udated inside the loops you will see only the last frame of the animation at the end of draw().)

Instead you have to use the looping of draw() itself and get rid of the while loop.

5 Likes