Adjusting for variable frame rate to prevent jitter

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
Abraxas)
Posts: 227
Joined: Sun Oct 18, 2009 7:24 am

Adjusting for variable frame rate to prevent jitter

Post by Abraxas) »

I had a problem, and I thought I would share with the community my solution in case anyone wanted some thoughts on the issue.

Here is the setup:

You have a node that's moving at a constantly changing velocity.
You have a dummy camera that snaps every frame to a spherical position around the node (that means two angles and a radius).
You have a camera that softmoves to the dummy position.
Now throw in a dramatically variable framerate.

What you end up with is jittering up and down your screen. Because the framerate is changing (and in my case it was due to a 4hz calculation event) you get all kinds of ugly jitter.

I do the following to smooth things out:

In my main loop:

Code: Select all

                curtime = device->getTimer()->getRealTime();
                prevte = te;
                oldte = (curtime - prevtime);   
                prevtime = curtime; 
                te = prevte + (oldte-prevte)*0.05;
 
                //std::cout << te << "\t";
 
                if (te > 25) te = 25;
for the camera:

Code: Select all

cameragoto = vector3df(obj->plane->parent->getAbsolutePosition()) - vector3df(  cameradistance*cos(cameraanglex)*cos(cameraangley) ,cameradistance*sin(cameraangley) ,  cameradistance*sin(cameraanglex)*cos(cameraangley));
 
 
 
    // Method 1: move camera a factor of distance vector.
        // Disadvantages: can overshoot.
vector3df cameradist = vector3df(camera->getAbsolutePosition()-cameragoto);
 
vector3df correction = cameradist*0.08*te;
 
if  (cameradist.getLengthSQ() > .000004) 
    camera->setPosition(camera->getAbsolutePosition() - correction  );
else    camera->setPosition(cameragoto);
 
    // Method 2: move camera a fraction of distance vector
//camera->setPosition( cpos + (cameragoto-cpos)*0.5 );
 
camera->setTarget(camera->getTarget() -  (camera->getTarget()- obj->plane->p)*.9 );
The result is a super smooth camera. You might be wondering if real-time events would be significantly affected by this, so I set up a timer and compared it with the real time, and the difference was always within 10%.

The point of this code is if you have periodic events that take more than a few normal frame times (20ms?) you might experience strong jitter. This was my solution, and the camera feels REALLY smooth.
Post Reply