Move gravity calculation into a generic function