Because soldiers didn't just rush blindly into battle - contrary to what every film/television show portrays. They'd be in formations (close or loose) and would stay in those formations because they'd know their flanks and rear were covered by other men in formation. Now there were plenty of situations where friendly forces did attack each other by mistake - usually if a wing defeated the enemy, chased them off the field and then returned to a battlefield where the remaining forces had moved (e.g. the Battle of Barnet).