我正在使用LWJGL和Slick Utils创建游戏。我正在尝试将动画纹理加载为单个PNG图像中包含的一组帧。
我试图弄清楚如何使用Slick来获取子图像,但到目前为止我能够在主题上找到的所有内容都是使用BufferedImages在Slick之外进行的。我想知道是否有办法使用Slick Utils库来实现这一点,因为到目前为止我项目中的所有图像加载代码都使用了Slick。
答案 0 :(得分:0)
当然,Slick提供了一种方法。如果您查看org.newdawn.slick.SpriteSheet.initImpl()
及更晚org.newdawn.slick.SpriteSheet.getSprite()
,您会注意到org.newdawn.slick.Image.getSubImage()
如何用于快速提取现有图片的特定部分。
<强> SpriteSheet.java 强>
protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth()-(margin*2) - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight()-(margin*2) - th) / (th + spacing)) + 1;
if ((getHeight() - th) % (th+spacing) != 0) {
tilesDown++;
}
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
//extract parts of the main image and store them in an array as sprites
subImages[x][y] = getSprite(x,y);
}
}
}
/**
* Get a sprite at a particular cell on the sprite sheet
*
* @param x The x position of the cell on the sprite sheet
* @param y The y position of the cell on the sprite sheet
* @return The single image from the sprite sheet
*/
public Image getSprite(int x, int y) {
target.init();
initImpl();
if ((x < 0) || (x >= subImages.length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
if ((y < 0) || (y >= subImages[0].length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
//Call Image.getSubImage() to get a portion of the image
return target.getSubImage(x*(tw+spacing) + margin, y*(th+spacing) + margin,tw,th);
}
您应该可以将其用作参考。我记得已经将Slick捆绑的Tiled渲染器完全移植到Java2D一次,使用旧的PixelGrabber来提取精灵。
如果您决定使用SpriteSheet
,可以在org.newdawn.slick.tiled.Layer.render()
中找到使用示例:
<强> Layer.java 强>
public void render(int x, int y, int sx, int sy, int width, int ty,
boolean lineByLine, int mapTileWidth, int mapTileHeight) {
for (int tileset = 0; tileset < map.getTileSetCount(); tileset++) {
TileSet set = null;
for (int tx = 0; tx < width; tx++) {
if ((sx + tx < 0) || (sy + ty < 0)) {
continue;
}
if ((sx + tx >= this.width) || (sy + ty >= this.height)) {
continue;
}
if (data[sx + tx][sy + ty][0] == tileset) {
if (set == null) {
set = map.getTileSet(tileset);
set.tiles.startUse();
}
int sheetX = set.getTileX(data[sx + tx][sy + ty][1]);
int sheetY = set.getTileY(data[sx + tx][sy + ty][1]);
int tileOffsetY = set.tileHeight - mapTileHeight;
//Call SpriteSheet.renderInUse() to render the sprite cached at slot [sheetX, sheetY]
set.tiles.renderInUse(x + (tx * mapTileWidth), y
+ (ty * mapTileHeight) - tileOffsetY, sheetX,
sheetY);
}
}
if (lineByLine) {
if (set != null) {
set.tiles.endUse();
set = null;
}
map.renderedLine(ty, ty + sy, index);
}
if (set != null) {
set.tiles.endUse();
}
}
}
<强> SpriteSheet.java 强>
public void renderInUse(int x,int y,int sx,int sy) {
//Draw the selected sprite at (x,y), using the width/height defined for this SpriteSheet
subImages[sx][sy].drawEmbedded(x, y, tw, th);
}
希望这会对你有所帮助。