简体   繁体   中英

JavaScript sprite sheet

I have a sprite sheet (png file) with 27 elements with equal spaces in between each element

+----------------+
| 1      2      3           
| 4      5      6
|
|
|
|
|
|
|
| 24     25     26

i want to insert all elements to array i figured out a way to do this it works fine

var ElemObjects = [];
ElemObjects.push(new Elem(0,0));
ElemObjects.push(new Elem(380,0));
ElemObjects.push(new Elem(760,0));
ElemObjects.push(new Elem(0,340));
ElemObjects.push(new Elem(380,340));
ElemObjects.push(new Elem(760,340));
ElemObjects.push(new Elem(0,680))
ElemObjects.push(new Elem(380,680))
ElemObjects.push(new Elem(760,680))

and so on

i want to do the same thing using a for loop my problem is with the logic i dont know have to change the x and y coordinates inside the for loop

for(var i =0; i < 26; i++){
    ElemObjects[ElemObjects.length] = new Elem(Xsr,Ysr);
    Xsr=Xsr+380;
}

any suggestions

Take a look at the modulo operator: http://en.wikipedia.org/wiki/Modulo_operation

// x is equal to block width times current x position
Xsr = 380*(i%3)

Make the position calculations based on the i value in the loop. Something like this should work:

for (var i =0; i < 26; i++) {
    var xModifier = i%3;
    var yModifier = Math.floor(i/3);

    ElemObjects[ElemObjects.length] = new Elem(380 * xModifier, 340 * yModifier);
}

That should get you the correct values that you need as you cycle through the list. The xModifier is based on the remainder left after you divide the current i value by 3, and yModifier is based off of how many times 3 will go evenly into the current i value. Here's the output, when sent to the console:

0, 0
380, 0
760, 0
0, 340
380, 340
760, 340
0, 680
380, 680
760, 680
0, 1020
380, 1020
760, 1020
0, 1360
380, 1360
760, 1360
0, 1700
380, 1700
760, 1700
0, 2040
380, 2040
760, 2040
0, 2380
380, 2380
760, 2380
0, 2720
380, 2720

If you have spriteWidth, spriteHeight, imageWidth, imageHeight, then code can look like :

var columnCount = imageWidth  / spriteWidth  ; 
var lineCount   = imageHeight / spriteHeight ; 

if (columnCount != Math.floor(columnCount)) throw ('sprite and image width don't match');
if (lineCount   != Math.floor(lineCount))   throw ('sprite and image height don't match');

for (var line=0; line<lineCount; line++) 
     for (var col=0; col<columnCount; col++) {

        // coordinates of the sprite  : ( col * spriteWidth; line*spriteHeight ) 
        // linear index of the sprite : ( line * columnCount ) + col 

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM