Java 2d game – Issues with delta time and collision

Java 2d game – Issues with delta time and collision

The easiest way would be to consider that if you want a constant displacement with a constant velocity you can scale all the deltas relative to the delta of 30 FPS like so:


So if you run at 60 FPS but want the same displacement as on 30FPS alpha would be (1/30)/(1/60) = 2

Remove vx = vx*delta;
vy = vy*delta;

and change your position update to

alpha = (1.0/30)*delta;
positionx += alpha*vx*speed;
positiony += alpha*vy*speed;

This is only a crude solution, let me know how it works, I will drop in later and update for a more correct solution (taking into account that delta is not always 1/FPS due to rendering and computation taking some time).

Edit: Variable delta will come later. But some optimizations:

  1. You dont need to construct a rectangle in both Y and X for collisiondetection, try drawing two rectangles, if they intersect they do so on both axis. Just create a rectangle from vx + posx, vy+posy and check for intersection with this.
  2. The above should half your collisionchecks. For further optimization consider using a QuadTree an implementation can be found here.

  3. For the problem of blocky collision testing (where you stop X pixels from the blocking object). You can do the following, in pseudocode:

     if(new position will make this colide)
       while(this.position is more than one pixel away from blocking object)
         keep moving one pixel

This will make you stop 1px from the target.

Java 2d game – Issues with delta time and collision

Leave a Reply

Your email address will not be published. Required fields are marked *