Optimality Conditions for Mechanical Impacts