I’m making my first game in canvas/JS and I’m running into an issue with function constructors. We’re trying to make it so that the Enemy object randomly takes one of two sprites on creation. Here’s a snippet of our code:
function Enemy() {
// Boilerplate stuff omitted. Relevant bit:
if (randomFromTo(1,50)%2 === 0) { // Assume this function works correctly
this.sprite.src = "images/scientist_1.png";
} else {
this.sprite.src = "images/scientist_2.png";
}
}
var enemy1 = new Enemy();
var enemy2 = new Enemy(); // etc
It seems straightforward enough, but it ends up with every enemy object having the same sprite. I have no idea why this would happen – if I put console log message in the appropriate places, it logs the correct choices, but every enemy ends up with the same sprite anyways. So what’s the best way to go about this, assuming it’s possible? Thanks!
If this.sprite is outside of Enemy object you are probably overwritting it each time. The value you get is then the last one.
After viewing your code: Values in the prototype are shared by all instances. You should put instance related state in the instance (function) itself.
In this case put
in Enemy() {…}