Search code examples
javascripthtmlvariablesgame-engineincrement

trigger code after x amount of increments


thanks for looking into this for me. The issue I am facing is this: I am keeping track of a variables value, i want to trigger blocks of code after certain values are reached.

currently I am using a switch statement but I am looking for something dynamic.

Example I have now:

class className{
  constructor(param){

  this.param = param

  switch(param.x){
    case 25:
      param.y += 0.1;
      break;
    case 50:
      y += 0.1;
      break;
    case 75:
      y += 0.1;
      break;
    }
  }

As you can see i want run a block of code after the value of X increments by 25 to manually code each block becomes tedious i want the same code to run every time the value of x increments by 25 x has no limit and this increments infinitely so i was looking for some kind of infinite loop or something does anyone know what I can use for this particular situation

If i could right it like this:

param.x.forEach(25){
  param.y += 0.1;
}

I did try this above but to no avail it did not work lol how can i do this guys any help please?


Solution

  • You could do the calculation like this (x % 25) == 0

    var y = 0;
    var x = 0;
    
    function trig() {
      x++;
      console.log(x)
      if ((x % 25) == 0) {
        y += 0.1;
        console.log(y, x)
      }
    }
    
    setInterval(() => {
      trig()
    }, 100)

    ON Class

    class className {
      constructor(param) {
        this.param = param
      }
      inc() {
        this.param.x++;
        if ((this.param.x % 25) == 0) {
          this.param.y += 0.1;
        }
      }
    
      //you could call the inc() function on you click or activity
    }