I would like to implement an object for my spritesheets in Javascript.
I'm very new to this language and game-developement so I dont really know how to do it.
My guess is I set spritesize to 16, use that to divide as many times as it fits on the spritesheet and store this value as "spritesheet". Then a for(i=0;i<spritesheet.length;i++)
loop running saving the number of sprites.
Then tile = new Image();
and tile.src = spritesheet[i]
to store the individual sprites based on their coordinates on the spritesheet.
My problem is how could I loop trough the spritesheet and make an array of that? The result should be similar to:
sprite.sprites = Array(
"0",
"1"
);
If possible this would be done with one single object that i only access once, and the tile array would be stored for later reference.
I couldn't find anything similar searching for "javascript spritesheet".
Edit 2: I've come a long bit since I first posted this question and this is what I've come up with so far:
function Sprite(){
this.size = 16;
this.spritesheet = new Image();
this.spritesheet.src = 'spritesheet.png';
this.spriteCount = this.spritesheet.height / this.spritesheet.width;
this.spriteIndex = 0;
var sprites = new Array();
for(i=0;i<this.spriteCount;i++){
sprites.push(this.spriteIndex); // Could insert pretty much whatever I want
this.spriteIndex++;
alert('spriteIndex # ' + sprites[i] + ' pushed');
}
}
var sprite = new Sprite();
The alert method is only for testing, it alerts from 0 and up giving me usable X and Y values for the drawing (when multiplyed by size). If anyone has improvements please let me know.
Edit 3: I still have some trouble with the array. How would i access the index of it? For example the first sprite should give me sprite.sprites[0] second sprite sprite.sprites[1].
sprites
array, you have to usethis.sprites
instead of justsprites
to be able to access it outside the function. \$\endgroup\$this.spriteCount = this.spritesheet.height / this.spritesheet.width;
doesn't make a lot of sense, it would only work for a single column sprite sheet of square sprites. And by the way,imageelement.height
andwidth
only work when the image is loaded. As soon as you hit the internet with lag your code will fail at that point as the image isn't loaded when you ask for it's dimensions. You could wait for it'sonload
event to fire, but it would be a lot simpler to just pass the values along with the url. \$\endgroup\$