JS function Math.hypot(dx, dy) works but variables reset if clicked twice

Twine Version: Latest of twine and Sugarcube

I have state variables magX and MagY. both start at 1.
Links send a direction variable to js where a function calculates the distance to the target.
The below code works but if the player clicks the same link twice, the value is not incremented.

Links:
:: maneuver
You're within <<= $distance >> moves of the glowing light. 
<<run setup.setSel($dir)>>
[[Move Forward|maneuver][$dir to 'f']]<br />
[[Move Left|maneuver][$dir  to 'l']]<br />
[[Move Backward|maneuver][$dir to 'b']]<br />
[[Move Right|maneuver][$dir to 'r']]<br />

This is the JS

function distanceToTarget(x1, y1) {
  var sv = State.variables;
  //target
  const x2 = 4;
  const y2 = 5;

  const dx = x2 - x1;
  const dy = y2 - y1;
  const c = Math.hypot(dx, dy);
  sv.distance = c;
  console.log(c);
}

setup.setSel = function(val){
  var sv = State.variables;
  let x1 = sv.magX;
  let y1 = sv.magY;
  console.log("vars", x1, y1);
  if(val === 'f'){
    y1++;
  }
  else if(val === 'l'){ 
    x1--;
  }
  else if(val === 'b'){
    y1--;
  }
  else if(val === 'r'){
    x1++;
  }
  distanceToTarget(x1, y1)
  console.log(x1,y1)
}
1 Like

Your problem is that your function changes x1 and y1, not $magX and $magY. The variables x1 and y1 only exist inside the setup.setSel() function. This means that no matter what the player clicks their position never actually changes, so for the same value of $dir the function always returns the same thing. You should replace x1 with sv.magX and y1 with sv.magY.

Incidentally, in order to display the correct distance you need to call setup.setSel() before printing $distance. Otherwise it’ll display the distance for the previous turn. You can simply swap the first two lines of the maneuver passage.

1 Like

Thank you! Updated function below.

setup.setSel = function(val){
  var sv = State.variables;

  if(val === 'f'){
    sv.magY++;
  }
  else if(val === 'l'){ 
    sv.magX--;
  }
  else if(val === 'b'){
    sv.magY--;
  }
  else if(val === 'r'){
    sv.magX++;
  }
  distanceToTarget(sv.magX,sv.magY)

}
1 Like