【问题标题】:Scala with LibGDX outputs error when creating Animation创建动画时带有 LibGDX 的 Scala 输出错误
【发布时间】:2021-11-28 14:20:18
【问题描述】:

我开始使用 Scala 进行编程,我决定使用 libgdx 制作一个非常简单的游戏。我已经创建了这个类:

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()
  }
}

(对不起,我现在只是在尝试)

如您所见,帧的类型是 Array[TextureRegion]。在 libgdx Animation Class 的文档中,我可以看到我应该能够使用这种类型调用 Animation 的构造函数,但是 intellij 输出:

[...]\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)

我不知道发生了什么。就我(有限)的理解而言,它似乎正在尝试使用构造函数的不同重载,但我不知道为什么也不知道如何解决它。

【问题讨论】:

    标签: java scala libgdx


    【解决方案1】:

    是的,Scala 编译器在这里很混乱,因为构造函数想要一个 gdx 数组,而不是 Java 数组(查看documentation)。 一种可能的解决方法是使用 var arg 语法:

    walkAnimation = new Animation(1f/4f, frames:_*)
    

    这样,它选择了这个构造函数:

    Animation(float frameDuration, T... keyFrames)
    

    或者,如果您愿意,可以直接使用 GDX 数组类:

    
    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)
      
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 2017-06-06
      相关资源
      最近更新 更多