austingray / canvas-game-engine

An HTML 5 canvas game engine.
2 stars 0 forks source link

window.setTimeout in character animations #5

Open austingray opened 5 years ago

austingray commented 5 years ago

Character animation/easing from position to position relies on window.setTimeout to calculate character positions.

For NPC movements:

    this.npcMovementTimer = window.setTimeout(() => {
      // get some potential target vals
      const targetX = (Math.random() * 4 - 2) * this.maxSpeed;
      const targetY = (Math.random() * 4 - 2) * this.maxSpeed;

      this.targetX = this.x + targetX;
      this.targetXTimerHandler(targetX > 0 ? 1 : 3);
      this.targetY = this.y + targetY;
      this.targetYTimerHandler(targetY > 0 ? 2 : 0);

      this.doMovement();
    }, msTilNextMove);

and for actual player movement:

    this.targetXTimer = setTimeout(() => {
      // calculate what the new x should be
      const newX = dir === 1 // right
        ? this.x + (difference / this.inputCooldown)
        : this.x - (difference / this.inputCooldown); 

      // handle collision
      const collision = this.map.getCollision(newX, this.y);

      if (collision) {
        this.targetX = this.x;
        difference = 0;
      } else {
        this.x = newX;
      }

      this.afterEaseMovement();

      // if we're not close enough to the target Y, keep moving
      if (difference > 1) {
        this.targetXTimerHandler(dir, this.map);
      }
    }, difference / this.inputCooldown);

The implementation on these movements has a potential for mini "bursts" of clearTimeout() / setTimeout() per character as the character eases in/out of their target positions.

I think this needs to be refactored for performance and portability. We should look at the characterBaseClass draw() method as a candidate for calculating and update the character's position.