2

我有一个包含 27 个元素的精灵表(png 文件),每个元素之间的空格相等

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

有什么建议么

4

3 回答 3

2

看看模运算符:http ://en.wikipedia.org/wiki/Modulo_operation

// x is equal to block width times current x position
Xsr = 380*(i%3)
于 2013-11-13T00:20:40.703 回答
2

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 后剩下的余数,并且基于yModifier3 将平均进入当前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
于 2013-11-13T00:20:51.283 回答
1

如果你有 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 

     }
于 2013-11-13T00:25:54.597 回答