DEADSOFTWARE

CaveGame in kotlin
[cavedroid.git] / core / src / ru / deadsoftware / cavedroid / game / input / Joystick.kt
1 package ru.deadsoftware.cavedroid.game.input
3 import com.badlogic.gdx.math.Vector2
4 import com.badlogic.gdx.utils.TimeUtils
6 class Joystick(
7 private val value: Float,
8 ) {
10 var active = false
11 private set
12 var centerX = 0f
13 private set
14 var centerY = 0f
15 private set
17 var activeX = 0f
18 private set
19 var activeY = 0f
20 private set
22 var pointer = 0
23 private set
25 private val stickVector = Vector2()
27 private var activateTimeMs = 0L
29 fun activate(touchX: Float, touchY: Float, pointer: Int) {
30 active = true
31 centerX = touchX
32 centerY = touchY
33 activateTimeMs = TimeUtils.millis()
34 this.pointer = pointer
35 }
37 fun deactivate() {
38 active = false
39 }
41 fun getVelocityVector(): Vector2 {
42 if (!active) {
43 return Vector2.Zero
44 }
45 return Vector2(
46 stickVector.x * value,
47 stickVector.y * value
48 )
49 }
51 fun updateState(touchX: Float, touchY: Float) {
52 if (!active) {
53 return
54 }
56 stickVector.x = touchX - centerX
57 stickVector.y = touchY - centerY
58 stickVector.clamp(0f, RADIUS)
60 activeX = centerX + stickVector.x
61 activeY = centerY + stickVector.y
63 stickVector.x /= RADIUS
64 stickVector.y /= RADIUS
65 }
67 companion object {
68 const val RADIUS = 48f
69 const val SIZE = RADIUS * 2
70 const val STICK_SIZE = 32f
71 }
73 }