aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/CameraController.kt
blob: c2885debe9702226cc751055db3663fdb8c56e93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import kotlinx.browser.document
import org.w3c.dom.HTMLButtonElement

class CameraController(
  private val camera: Camera,
  private val moveSpeed: Double,
  private val rotateSpeed: Int,
  private val xMax: Int,
  private val yMax: Int,
  private val afterInput: () -> Unit
) {

  init {
    document.onkeydown = { keyHandler(it.code) }
    (document.getElementById("up") as HTMLButtonElement).onclick = { moveForward() }
    (document.getElementById("down") as HTMLButtonElement).onclick = { moveBack() }
    (document.getElementById("left") as HTMLButtonElement).onclick = { rotateAntiClockwise() }
    (document.getElementById("right") as HTMLButtonElement).onclick = { rotateClockwise() }
  }

  private fun keyHandler(code: String) {
    when (code) {
      "KeyW" -> moveForward()
      "KeyS" -> moveBack()
      "KeyA" -> rotateAntiClockwise()
      "KeyD" -> rotateClockwise()
    }
  }

  private fun moveForward() {
    val cameraCos = camera.rotation.cosine() * moveSpeed
    val cameraSin = camera.rotation.sine() * moveSpeed
    camera.xPos += cameraCos
    camera.yPos += cameraSin
    boundsCheck(camera)
    afterInput()
  }

  private fun moveBack() {
    val cameraCos = camera.rotation.cosine() * moveSpeed
    val cameraSin = camera.rotation.sine() * moveSpeed
    camera.xPos -= cameraCos
    camera.yPos -= cameraSin
    boundsCheck(camera)
    afterInput()
  }

  private fun rotateClockwise() {
    camera.rotation += rotateSpeed
    afterInput()
  }

  private fun rotateAntiClockwise() {
    camera.rotation -= rotateSpeed
    afterInput()
  }

  private fun boundsCheck(camera: Camera) {
    camera.xPos = clamp(camera.xPos, xMax)
    camera.yPos = clamp(camera.yPos, yMax)
  }

  private fun clamp(position: Double, max: Int): Double {
    return when {
      position < 1 -> 1.0
      position > max -> max.toDouble()
      else -> position
    }
  }

}