簡體   English   中英

JavaScript Sprite工作表

[英]JavaScript sprite sheet

我有一個精靈表(png文件),其中包含27個元素,每個元素之間的間距相等

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

我想將所有元素插入數組中,我想出了一種方法可以正常工作

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))

等等

我想使用for循環做同樣的事情,我的問題是我不知道必須更改for循環內的x和y坐標的邏輯

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

有什么建議么

看一下模運算符: http : //en.wikipedia.org/wiki/Modulo_operation

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

根據循環中的i值進行位置計算。 這樣的事情應該起作用:

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);
}

這將為您提供遍歷列表所需的正確值。 xModifier基於將當前i值除以3后剩下的余數,而yModifier基於3均勻地乘以當前i值的次數。 這是發送到控制台后的輸出:

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

如果您具有spriteWidth,spriteHeight,imageWidth,imageHeight,則代碼如下所示:

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 

     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM