Added boundary checking to animate function