我正在使用Kotlin语言+ LibGDX库制作游戏。
Kotlin版本:1.1.2-4
LibGDX版本:1.9.6
正如官方文件所说
"[] operation stands for calls to member functions get() and set()."
但是,当我尝试运行这行代码时:
body.userData = animations[state[e].currentState]!!.keyFrames[frame]
我得到了这个错误:
Exception in thread "LWJGL Application" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.badlogic.gdx.graphics.g2d.TextureRegion;
但是,当我将[]更改为get()时:
body.userData = animations[state[e].currentState]!!.keyFrames.get(frame)
一切都会好起来的。
PS:"frame“是角度,转换为Int。
UPD:我稍微修改了一下代码
val animation: Animation = anim[e].animations[state[e].currentState]!!
val tex = animation.keyFrames[frame] // Get exception on this line anyway
body[e].body.userData = tex
“e”是来自Ashley的实体引用。“body”、“anim”和“state”是Ashley组件映射器。
对于那些不知道LibGDX是什么的人来说,这里是一个动画类,这里的keyFrames只是一个Java Array。
更新2:我注意到只有当我使用这个构造函数时才会出现问题:
Animation(float frameDuration, Array<? extends T> keyFrames)
看起来像是可互操作的问题。
发布于 2017-09-16 17:19:37
强制转换错误对象无法转换为TextureRegion
public operator fun get(index: Int): T
返回位于kotlin.Array
的指定索引处的数组元素。
T[] keyFrames
是Animation
类中T类型的数组。
我以这种方式声明,我没有强制转换错误/异常。:
lateinit var ani:Animation<TextureRegion>
ani = Animation(.1f,TextureRegion(Texture("badlogic.jpg")))
val y= ani.keyFrames.get(0) // -> y is a TextureRegion
替换为索引运算符
val x=ani.keyFrames[0] // -> x is a TextureRegion
然后指定给body userData。
val world = World(Vector2(10f,10f),false)
val body = world.createBody(BodyDef())
body.userData = y // -> Either you use x or y you always get sprite
var sprite=Sprite(body.userData as TextureRegion?)
https://stackoverflow.com/questions/46251441
复制相似问题