Refactored raycast method