Refactored collision detection algorithm