Search code examples
kotlinopenglcollision-detectiontransformation

Problem with simple rectangle collison in OpenGL


I try to implement collision detection and collision effects. This is my code for collision detection:

    fun collisionDetection(objcect : Renderable?, object2 : Renderable?) : Boolean {
    var collisionX : Boolean = objcect?.getPosition()?.x?.plus(quadSizeX)!! >= object2?.getPosition()?.x!! && object2?.getPosition()?.x?.plus(quadSizeX)!! >= objcect?.getPosition()?.x!!
    var collisionY : Boolean = objcect?.getPosition()?.y?.plus(quadSizeY)!! >= object2?.getPosition()?.y!! && object2?.getPosition()?.y?.plus(quadSizeY)!! >= objcect?.getPosition()?.y!!
    var collisionZ : Boolean = objcect?.getPosition()?.z?.plus(quadSizeZ)!! >= object2?.getPosition()?.z!! && object2?.getPosition()?.z?.plus(quadSizeZ)!! >= objcect?.getPosition()?.z!!

    return collisionX && collisionY && collisionZ }

This seems to work, when used with overlapping objects set to overlapping values by transformations. This way

        wall.translateLocal(Vector3f(0.0f, 1.0f, -8.0f))

and

        wall2.translateLocal(Vector3f(0.0f, 2.0f, -8.0f))

collisionDetection is true.

When moving wall2 on the z-axis with a different starting point and speed, but x and y position are the same, the effect of the collision should be that wall2 stops moving, when z position of both objects is equal. I tried it this way in the main loop (and many other ways...), but it is still not working:

fun render(dt: Float, t: Float) {
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)


        staticShader.use()
        camera.bind(staticShader)

        wall.render(staticShader)
        wall2.render(staticShader)

        if (collisionDetection(wall, wall2) == true) {
            wall2.getPosition()
        }
        else {wall2.translateLocal(Vector3f(0.0f, 0.0f, -t.toFloat()* 0.001f))}

}

I have no idea now, what is wrong and how to fix it. It seems like the collisionDetection function doesn't get information about the changing positions on the z-axis of the wall2. Or maybe I need a different approach.


Solution

  • Everything works fine now. Forgot to calculate QuadSize for the second object. This results in two objects on the same z.coordinate.Nothing has been wrong with the function for detecting collisions.