use 'see inside' to play around with AI level and movement speed, notes in the code will explain everything else. This is the same algorithm that the Five Nights at Freddy's games use to determine when the animatronics move. In the games when they move they head to an adjacent room (or appear directly outside the door)
Credits to Scott Cawthon.