What is the correct order of operations for collision detection and response?
<p>I am trying to make a 2D game engine, but I can't seem to get collisions to work all the time (Often times things get stuck or pass through each other). Without getting into the code too much, here is the order in which I am updating.</p>

<ol>
<li>Get user input and update the player velocity</li>
<li>Save the position for each entity, then move the velocity / update interval units</li>
<li>Check each movable entity for collisions against all other entities.  If the entity collides with something, it is moved to its old position and the new velocities are set for both colliding entities.</li>
</ol>

<p>The collision impulse is calculated in this function:</p>

<pre><code>private static void CollisionImpulse(PhysicsEntity a, PhysicsEntity b)
    {
        var relative = b.Velocity.Vector - a.Velocity.Vector;
        var normal = Vector2.Normalize(relative);
        var e = Math.Min(a.Material.Elasticity, b.Material.Elasticity);
        var j = (-(1 + e) * Vector2.Dot(relative, normal)) /
                (Vector2.Dot(normal, normal) * (a.InverseMass + b.InverseMass));
        if (double.IsNaN(j)) return;

        var velocityA = normal * (float) (j / a.Mass);
        var velocityB = normal * (float) (j / b.Mass);

        a.Velocity.X -= velocityA.X;
        a.Velocity.Y -= velocityA.Y;

        if (!b.Movable) return;
        b.Velocity.X += velocityB.X;
        b.Velocity.Y += velocityB.Y;
        b.Position = b.OldPosition;
    }
</code></pre>

<p>and this is the function to check for the collisions:</p>

<pre><code>public override void Update()
        {
            foreach (var entity in Universe.PhysicsEntities)
            {
                if (entity.Equals(this) || entity.Collided) continue;
                CollisionResolution.ResolveCollision(this, entity);
                if (!Collided) continue;
                Position = OldPosition;
                break;
            }
        }
</code></pre>

<p>I have been trying to tweak the code for a few days, but I cannot figure out what is wrong.  I was hoping some fresh eyes could shed some light on my dilemma.</p>