Energy-optimal collision-free catching of flying targets with nonlinear optimization and learning