Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Game Development: Collision Detection Failing

I am currently developing a game for Android, and I would like your expertise on an issue that I have been having.

Background:

  1. My game incorporates frame rate independent motion, which takes into account the delta time value before performing necessary Velocity calculations.

  2. The game is a traditional 2D platformer.

The Issue:

Here's my issue (simplified). Let's pretend that my character is a square standing on top of a platform (with "gravity" being a constant downward velocity of characterVelocityDown).

I have defined the collision detection as follows (assuming Y axis points downwards):

Given characterFootY is the y-coordinate of the base of my square character, platformSurfaceY is the upper y-coordinate of my platform, and platformBaseY is the lower y-coordinate of my platform:

  if (characterFootY + characterVelocityDown > platformSurfaceY && characterFootY + characterDy < platformBaseY) {

                    //Collision Is True
                    characterFootY = platformSurfaceY;
                    characterVelocityDown = 0;

                } else{ 
                    characterVelocityDown = deltaTime * 6;

This approach works perfectly fine when the game is running at regular speed; however, if the game slows down, the deltaTime (which is the elapsed time between the previous frame and the current frame) becomes large, and characterFootY + characterVelocityDown exceed the boundaries that define collision detection and the character just falls straight through (as if teleporting).

How should I approach this issue to prevent this?

Thanks in advance for your help and I am looking forward to learning from you!

like image 396
SeveN Avatar asked Nov 03 '22 22:11

SeveN


1 Answers

What you need to do is to run your physics loop with constant delta time and iterate it as many time as it need with current tick.

const float PHYSICS_TICK = 1/60.f; // 60 FPS
void Update( float dt )
{
    m_dt += dt;
    while( m_dt > PHYSICS_TICK )
    {
        UpdatePhysics( PHYSICS_TICK );
        m_dt -= PHYSICS_TICK;
    }
}

There are various technics used to handle the tick left ( m_dt )
Caps for miniumum tick and maximum tick are also a must.

like image 90
Wojciech Avatar answered Nov 11 '22 10:11

Wojciech