Skip to content

Instantly share code, notes, and snippets.

@TobseF
Created February 25, 2022 10:26
Show Gist options
  • Save TobseF/988a4c01576e92ae3f02842bec5853c9 to your computer and use it in GitHub Desktop.
Save TobseF/988a4c01576e92ae3f02842bec5853c9 to your computer and use it in GitHub Desktop.
KorGE setup for super smooth player movement by keys or mouse-click
private var destination: Point = player.pos.copy()
private val playerSpeed = 6.0
private val step = 20
init {
addUpdater {
handeKeyboardControls()
}
addFixedUpdater(25.milliseconds) {
if (destination.distanceTo(player.pos) > playerSpeed) {
moveToDestination()
}
}
onClick {
destination.copyFrom(it.currentPosStage)
}
}
private fun handeKeyboardControls() {
if(anyMoveKeyIsPressed()){
resetDestination()
}
if (Key.UP.isPressed() || Key.W.isPressed()) {
moveUp()
}
if (Key.DOWN.isPressed() || Key.S.isPressed()) {
moveDown()
}
if (Key.LEFT.isPressed() || Key.A.isPressed()) {
moveLeft()
}
if (Key.RIGHT.isPressed() || Key.D.isPressed()) {
moveRight()
}
}
fun anyMoveKeyIsPressed() = (arrowKeys() + wasdKeys()).any { it.isPressed() }
private fun arrowKeys() = listOf(Key.UP, Key.DOWN, Key.LEFT, Key.RIGHT)
private fun wasdKeys() = listOf(Key.W, Key.A, Key.S, Key.S)
private fun Key.isPressed() = stage?.input?.keys?.get(this) ?: false
private fun moveLeft() {
destination.x -= step
}
private fun moveRight() {
destination.x += step
}
private fun moveDown() {
destination.y += step
}
private fun moveUp() {
destination.y -= step
}
private fun resetDestination() {
destination.copyFrom(player.pos)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment