How to get a value from a setter method?

Advertisements

I have this setter method that I got from a YouTube video by Coding with Adam:

class SpriteAnimation{
  images = [];
  constructor(fileNameTemplate, numberOfImages, timerCount, state, stopAtEnd) {
    for (let i = 1; i <= numberOfImages; i++) {
      const image = img(fileNameTemplate.replace("?", i));
      this.images.push(image);
    }
    this.timerCount = timerCount;
    this.timerCountDefault = this.timerCount;
    this.imageIndex = 0;
    this.state = state;
    this.stopAtEnd = stopAtEnd;
  }

  isFor(state) {
    return this.state === state;
  }

  reset() {
    this.imageIndex = 0;
  }

  getImage() {
    this.#setImageIndex();
    return this.images[this.imageIndex];
  }
  
  #setImageIndex() {
    this.timerCount--;
    if (this.timerCount <= 0 && !this.#shouldStop()) {
      this.timerCount = this.timerCountDefault;
      this.imageIndex++;
      if (this.imageIndex >= this.images.length) { 
        this.imageIndex = 0;
      }
    }
  }

  #shouldStop(){
    return this.stopAtEnd && this.imageIndex === this.images.length -1;
  }
}

I need to get the value of the imageIndex as the animation is playing so I thought I should get it through the #setImageIndex() method, but I don’t have any idea how.

I tried using a getter method for it:

  getImageIndex(){
    return this.imageIndex;
  }

But it only returned 0.

Any help is appreciated, thank you!

>Solution :

If you are only getting 0, it means that the imageIndex property is not being updated during the animation.
try this code

class SpriteAnimation {
  images = [];
  timerCount = 0;
  timerCountDefault = 0;
  imageIndex = 0;
  state = "";
  stopAtEnd = false;

  constructor(fileNameTemplate, numberOfImages, timerCount, state, stopAtEnd) {
  for (let i = 1; i <= numberOfImages; i++) {
  const image = img(fileNameTemplate.replace("?", i));
  this.images.push(image);
  }
  this.timerCount = timerCount;
  this.timerCountDefault = timerCount;
  this.state = state;
  this.stopAtEnd = stopAtEnd;
  }

  isFor(state) {
  return this.state === state;
  }

  reset() {
  this.imageIndex = 0;
  this.timerCount = this.timerCountDefault;
   }

  getImage() {
  this.timerCount--;
  if (this.timerCount <= 0 && !this.shouldStop()) {
  this.timerCount = this.timerCountDefault;
  this.imageIndex++;
  if (this.imageIndex >= this.images.length) {
    this.imageIndex = 0;
  }
  }
  return this.images[this.imageIndex];
  }

  getImageIndex() {
  return this.imageIndex;
   }

  shouldStop() {
  return this.stopAtEnd && this.imageIndex === this.images.length - 1;
   }
  }

Leave a ReplyCancel reply