Ray Rahke
05/17/2024, 10:59 AMwhen
, for the following
if (Gameengine.input.keysdown(Keys.W) {
// ..
}
if (Gameengine.input.keysdown(Keys.A) {
// ..
}
if (Gameengine.input.keysdown(Keys.S) {
// ..
}
if (Gameengine.input.keysdown(Keys.D) {
// ..
}
I want something like
when Gameengine.input.keysdown() {
Keys.W -> {}
Keys.A -> {}
Keys.S -> {}
Keys.D -> {}
}
I know why this is semantically incorrect. but is there an equivalent?Joffrey
05/17/2024, 11:01 AMGameengine.input.keysdown
defined? Can it return the set of keys that are pressed?
If those are directions in the game, you might not want a when
because both A
and W
could be pressed at the same time to go diagonally, right? In this case you might want to run both the branch for the A
and the one for the W
Ray Rahke
05/17/2024, 11:02 AMRay Rahke
05/17/2024, 11:04 AMwhen
is not right for player movement since you should be able to trigger both at the same timeRay Rahke
05/17/2024, 11:05 AMRay Rahke
05/17/2024, 11:05 AMRay Rahke
05/17/2024, 11:05 AMJoffrey
05/17/2024, 11:07 AMwhen
were valid for you (you only want one branch) and you had to use the API of GameEngine exactly as it is designed here, then I'm afraid the only when
-based option would be to use a subject-less when
like:
when {
Gameengine.input.keysdown(Keys.W) -> {}
Gameengine.input.keysdown(Keys.A) -> {}
Gameengine.input.keysdown(Keys.S) -> {}
Gameengine.input.keysdown(Keys.D) -> {}
}
But that's not helping much if your problem was the repetition.Joffrey
05/17/2024, 11:08 AMGameengine.input.keysdown()
returned a set of pressed keys instead, you could do things like:
val keysDown = GameEngine.input.keysdown() // assuming you could get a set here
when {
Keys.W in keysDown -> {}
Keys.A in keysDown -> {}
Keys.S in keysDown -> {}
Keys.D in keysDown -> {}
}
Joffrey
05/17/2024, 11:09 AMval keyHandlers = mapOf<Key, () -> Unit>(
Keys.W to { ... }
Keys.A to { ... }
Keys.S to { ... }
Keys.D to { ... }
)
val keysDown = GameEngine.input.keysdown() // still assuming you could get a set here
keysDown.forEach {
keyHandlers[it]?.invoke() // or use getValue to make it fail on unknown keys
}
Ray Rahke
05/17/2024, 11:12 AMYoussef Shoaib [MOD]
05/17/2024, 1:48 PMobject keysdown {
operator fun contains(key: Keys) = Gameengine.input.keysdown(key)
}
Then you can do:
when {
Keys.W in keysdown -> ...
Keys.A in keysdowm -> ...
}
Ruckus
05/17/2024, 8:41 PMfun Keys.isDown() = Gameengine.input.keysdown(this)
when {
Keys.W.isDown() -> ...
Keys.A.isDown() -> ...
}