Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

kotlin - Click on Sprite only gets detected for the first Sprite (LibGDX)

Currently I'm working on a game like Mau-Mau (card game). The inner workings of the game do their job, just like they should. But for some reason when the player is able to lay several cards the game only detects a mouse click on the first card which can be layed. The mouse clicks are detected like this:

private var screenX = -1
private var screenY = -1

override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
        if (button == Input.Buttons.LEFT) {
            this.screenX = screenX
            this.screenY = screenY
        }
        return false
    }

fun isCardClicked(card: Card): Boolean {
        if (card.getSprite().boundingRectangle.contains(screenX.toFloat(), (Gdx.graphics.height - screenY).toFloat())) {
            screenX = -1
            screenY = -1
            return true
        }
        screenX = -1
        screenY = -1
        return false
    }

The method isCardClicked() is called in my Game class:

while (cardIterator.hasNext() && !cardLayed) {
        val card = cardIterator.next()
        if (player.isPlayable(card, deliCard)) {
                if (inputHandler.isCardClicked(card)) {
                        println("player: $card")
                        deliStack.take(card)
                        cardIterator.remove()
                        cardLayed = true
                        changeTurns()
                }
        }
}

Does anybody know why I'm only able to lay the first layable card but not every other layable card in the player hand?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    fun isCardClicked(card: Card): Boolean {
        screenX = -1
        screenY = -1
        return card.getSprite().boundingRectangle.contains(screenX.toFloat(), (Gdx.graphics.height - screenY).toFloat())
    }

You're resetting screenX and screenY to -1 before checking any card. So only the card overlapping that point will ever return true, not the card under the click point.

And a side note...with Kotlin you don't have to manually use the iterator to be able to find and remove an item. Your loop could be replaced with:

val removedCard = cardList.removeFirstOrNull { card ->
    player.isPlayable(card, deliCard) && inputHandler.isCardClicked(card)
}
if (removedCard != null) {
    println("player: $card")
    deliStack.take(card)
    changeTurns()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...