Reputation: 452
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!
Upvotes: 0
Views: 494
Reputation: 22020
If you are initializing this.sprite
directly on the prototype, then all enemy objects share the same Image so each call to the constructor overwrites the image source of all enemies. So this does not work:
function Enemy()
{
this.sprite.src = ...someRandomizedUrl...
}
Enemy.prototype.sprite = new Image();
You have to do it like this:
function Enemy()
{
this.sprite = new Image();
this.sprite.src = ...someRandomizedUrl...
}
Your full source code is quite the same as the first code block (The wrong one) because all enemies share the same GameObject
and therefor they share the same sprite image. Initialize this.sprite
in the constructor of Enemy
and it works.
Upvotes: 1
Reputation: 32273
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
// Sprite
this.sprite = new Image();
this.sprite.src = "";
in Enemy() {...}
Upvotes: 1