Resetting Code-Newbie Coding

Hello… And alrighty, so the issue I’ve been having is that I can’t seem to figure out how to reset my code but with a certain variable changed after a specific event. For more clarification, I’m trying to reset the code after my character collides with an enemy, but with one less life

Player: function (img, x, y, w, h) {
//bunch of functional code regarding animation, location and other properties goes here and whatnot
this.lives = 3;
}

^^^Character variable stated in a separate file

if (entity.type === "enemy") {
            if (player.x < entity.x && player.y >= entity.y) {
                player.x = entity.x - player.w;
                player.lives -=1;
            }
        
            if (player.x > entity.x && player.y >= entity.y) {
                player.x = entity.x + entity.w;
                player.lives -=1;
            }

            if (player.y < entity.y && (player.x + player.w) > entity.x + 10 &&
                player.x < (entity.x + entity.w) - 10 && player.velY >= 0) {
                player.y = entity.y - player.h;
                player.velY = 0;
                jack.lives -=1;
            }
        }

^^^This is the already functional collision code/the event which I need to restart my code with…
I’ve tried the window.reload, but that resets everything, and renders the lives useless.
So yeah, any help regarding the above would greatly be appreciated!

Hi @billboxcar127, you could add a “reset” method to your player objects to (partially) revert them to their initial state:

var createPlayer = function (x, y) {
  return {
    lives: 3,

    reset: function () {
      this.x = x
      this.y = y
    }
  }
}

var player = createPlayer(0, 0)

player.reset()

The factory function creates a closure here, which maintains a reference to the initial values. If you’re using a constructor function instead, you might store the initial values to the object itself, like e.g.

var Player = function (x, y) {
  this.initial = {
    x: x,
    y: y
  }

  this.lives = 3
}

Player.prototype.reset = function () {
  this.x = this.initial.x
  this.y = this.initial.y
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.