aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/CameraController.kt
blob: a3508c1112d839b9392a4561c4a431bb168145e8 (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
import kotlinx.browser.document

class CameraController(
  private val camera: Camera,
  private val moveSpeed: Double = 0.5,
  private val rotateSpeed: Int = 5,
  private val afterInput: () -> Unit
) {

  init {
    document.onkeydown = { inputHandler(it.code) }
  }

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

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

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

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

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

}