繁体   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