How to initialise a variable once, instead of every time the function runs?

I have this code:

let step = 5;
let dir = -1;

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  // Setup canvas
  background(81);
  translate(width / 2, height / 2);

  drawArc(200, 0, 0);
  drawArc(100, 0, 0);
}

function drawArc(radius, h, k) {
  let points = new Array();
  let i = 0;

  // Generate the points of the arc
  for (let theta = TWO_PI; theta > PI; theta -= step / radius) {
    let x = h + radius * Math.cos(theta);
    let y = k - radius * Math.sin(theta);
    points.push(createVector(x, y));
  }

  // Draw the arc
  noFill();
  strokeWeight(1);
  stroke(255);
  beginShape();
  for (let point of points) {
    vertex(point.x, point.y);
  }
  endShape();

  // Draw the point
  strokeWeight(10);
  stroke(255);
  point(points[i].x, points[i].y);

  // Handle point movement
  if (i >= points.length - 1 || i <= 0) {
    dir *= -1;
  }

  i += dir;
}

Which draws a point along an arc. However I only want the variable i to be initialised once, for each arc. Setting it as a global variable will not do the trick. How do I achieve this? As right now, it sets i to 0 every time the drawArc() function runs so the point never moves.

Tagged:

Answers

  • Answer ✓

    I achieved this with classes.

  • Setting it as a global variable will not do the trick.

    Why not? Which variable are you talking about here?

  • I am talking about the i variable. I want a new i variable for every arc, so I used a new class for it and I got it working.

Sign In or Register to comment.