2017-09-16 24 views
1

我使用Kotlin語言+ LibGDX庫製作遊戲。Kotlin中的get和[]調用有什麼區別?

科特林版本: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;

然而,當我改變[]獲得():

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」是阿什利實體refrence。 「body」,「anim」和「state」是Ashley組件映射器。

對於那些不知道LibGDX在這裏的人是動畫類 這裏的keyFrames只是一個Java Array。

UPD 2: 我注意到,只有當我使用這個構造發生這個問題:

Animation(float frameDuration, Array<? extends T> keyFrames) 

貌似互操作問題。

+0

'keyFrames'的類型是什麼? –

+0

您正在使用哪種LibGDX版本? – Aryan

+0

@AbhishekAryan 1.9。6 – icarumbas

回答

0

鑄造誤差對象不能的kotlin.Array指定索引處被轉換爲TextureRegion

public operator fun get(index: Int): T 

返回的數組元素。

T[] keyFramesAnimation類中的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 

然後分配到身體用戶數據。

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?) 
+0

時,我得到了100個例外。我實際上並沒有明白你的意思。即使在這一行「val texture = animations [state [e] .currentState] !!。keyFrames [frame]」,我得到了異常。我不認爲我在這裏投了什麼東西。 – icarumbas

+0

什麼是動畫?它是動畫數組嗎?和'state [e] .currentState'? – Aryan

+0

動畫是HashMap >() – icarumbas

相關問題