Trying Kotlin: Virtual Camera

December 8, 2018

I had some fun over the last couple of weeks implementing a virtual camera in Kotlin. The idea for the camera was to move around a rendered 3D scene in any direction. So you can move it around, zoom in, zoom out and do diffrent translations around the scene.

The code is on Github virtual-camera

Here is a screenshot of one of the versions:

Camera

And you can see a short demo here:

camera

As evident by the demo the Cubes render a bit funny. The reason for that is probably math, and to be more precise there’s a lot of stuff being done to points presented in 3D space but before rendering we do the translations and transformations and than we present stuff in 2D (as this is what is needed to present it on the 2D canvas we have) and it all uses rounding so that can cause problems.

Here’s an example of how it gets done where you can clearly see how 3 dimensional point object gets projected onto a 2 dimensional plane.

fun projectTo2D(p : Point3D, context: DrawingContext) : Point2D {
    with (context) {
        val k = camera.planeDistance / (p.y - camera.y)
        val newX = (k * p.x + scene.x)
        val newZ = (scene.z - k * p.z)
        return Point2D(newX, newZ)
    }
}

One thing I like is how easy it is to understand the scene transformations.

fun rotateXLeft() {
    val cuboids = multiplyObjects(algebra.xRotation(-Scene.ANGULAR_STEP))
    this.objects = cuboids
}

fun rotateXRight() {
    val cuboids = multiplyObjects(algebra.xRotation(Scene.ANGULAR_STEP))
    this.objects = cuboids
}

It looks very expresive and it’s easy to understand what is going on.

The other thing I liked working on this was that even without the tests, it was fairy easy to quickly test ideas by just running the code and trying stuff. To be fair though having some tests for geometrical transformations would save us a lot of time at one point when we had to rewrite the way objects are represented.