I am starting programming with Scala and I decided to make a really simple game using libgdx. I have created this class:
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.{GL20, Texture}
import com.badlogic.gdx.Gdx
import com.badlogic.gdx
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.TextureRegion
class Game extends gdx.Game {
var batch: SpriteBatch = _
var walkSheet: Texture = _
var walkAnimation: Animation[TextureRegion] = _
var reg: TextureRegion = _
var stateTime: Float = _
def create(): Unit = {
batch = new SpriteBatch()
walkSheet = new Texture(Gdx.files.internal("assets/animations/slam with VFX.png"))
val frames: Array[TextureRegion] = TextureRegion.split(walkSheet, walkSheet.getWidth / 1, walkSheet.getHeight / 10).flatMap(_.toList)
walkAnimation = new Animation(1f/4f, frames)
}
override def render(): Unit = {
Gdx.gl.glClearColor(1f,1f,1f,1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
batch.begin()
stateTime = Gdx.graphics.getDeltaTime()
//println(stateTime)
reg = walkAnimation.getKeyFrame(stateTime, true)
batch.draw(reg, 0,0,reg.getRegionWidth*4, reg.getRegionHeight*4)
batch.end()
}
}
(sorry for the crappines, I am just trying things right now)
As you can see, frames' type is Array[TextureRegion]. In the documentation for the libgdx Animation Class I can see that I should be able to call the constructor of Animation with this type, but intellij outputs:
[...]\git\master\src\Main\scala\Game.scala:21:42
type mismatch;
found : Array[com.badlogic.gdx.graphics.g2d.TextureRegion]
required: com.badlogic.gdx.graphics.g2d.TextureRegion
walkAnimation = new Animation(1f/4f, frames)
I have no idea what is going on. To my (limited) understandig it seems that it is trying to use a different overload of the constructor, but I do not know why neither how to solve it.
CodePudding user response:
Yes, Scala compiler is quite confused here, because the constructor want a gdx array, not a Java array (look at the documentation). A possible workaround could be in using var arg syntax:
walkAnimation = new Animation(1f/4f, frames:_*)
In this way, it selects this constructor:
Animation(float frameDuration, T... keyFrames)
Or, if you prefer, you could use the GDX array class directly as:
import com.badlogic.gdx.utils.{Array => GDXArray}
val frames: GDXArray[TextureRegion] = new GDXArray(TextureRegion.split(walkSheet, walkSheet.getWidth / 1, walkSheet.getHeight / 10).flatMap(_.toList))
walkAnimation = new Animation(1f/4f, frames)