Fix gravity bug and some refactoring