Skip to content

Sprites

Perses Games edited this page Apr 26, 2017 · 3 revisions

Sprites/textures

All sprites/images are based on textures. We can load a texture like this:

  Textures.load("PLAYER", "img/PNG/playerShip2_red.png")

A screen will not render while there are textures loading, so you don't have to check if textures are loaded. But you can check this with Textures.ready().

You can use the texture like this:

  Textures["PLAYER"].queueDraw(x, y, scale, rotation)

This will only queue the texture in the draw buffer. To actually draw the texture call:

  Textures.render()

The buffer will be rendered once it is full. Every texture/image has it's own buffer, this reduces draw call to the video card and increases performance dramatically.

So if you are drawing a background make sure you call the render method before drawing the other sprites.

Usage example

Here is an example of how to use it in a Screen, please note:

  • Texture has a render method as well (no need to draw all the Textures)
  • We dispose the textures once we are done with them (to unload them from video memory)
class ExampleScreen: Screen() {
    val player: Texture by lazy { Textures["PLAYER"] }

    override fun loadResources() {
        Textures.load("PLAYER", "img/player.png")
    }

    override fun unloadResources() {
        Textures.dispose()
    }

    override fun update(time: Float, delta: Float) {
        // check inputs etc.
    }

    override fun render() {
        player.queueDraw(100f, 100f)

        player.render()
    }
}

Simple spritesheet

If you have an image with a animation on it, like this:

Explosion

You can draw one of the subimages with this method:

  Textures["PLAYER"].queueTileDraw(x, y, horizontalCount, verticalCount, frame, scale, rotation)

Where horizontal and vertical count are the number of sub-images respectively and the frame is the image to draw. The left top one having number 0, the one to the right number 1, etc.

So a class used to draw explosions might look like this:

class Explosion(
  var x: Float,
  var y: Float
) {
    val texture: Texture by lazy { Textures["EXPLOSION1"] }
    var frameTime = 0.016f
    var currentFrame = frameTime
    var frame = 0
    var frameCount = 81
    var dead = false

    override fun update(delta: Float) {
        currentFrame -= delta

        if (currentFrame < 0) {
            currentFrame += frameTime
            frame++
        }

        if (frame >= frameCount) {
            dead = true
        }
    }

    override fun draw() {
        if (!dead) {
            texture.queueTileDraw(x, y, 9, 9, frame, 1.5f)
        }
    }

}
Clone this wiki locally