In Candy Monster Game we have hungry monsters, we call them "Pateat". Pateats are very, very hungry and they want to eat you :). You have no weapons so you know that fighting a Pateat is not a good idea. So how can you escape? You will see on the some space candy flying over the universe, feeding the Pateat with it will make him not hungry. You must to be smart enough to make, the Pateat follow you and eat the candy that's on the path. Once the Pateat is not hungry you'll be able to advance.
To make a Pateat follow you we applied a chasing algorithm. When ever you are on the sight view field of the Pateat we will follow you. You can use the objects to hide from the Pateat.
We came out with a simple solution. Remember y = xm + b, the algebra formula that represent straight lines? We first create an offset vector, by subtracting the Pateat position from the player position. The offset vector has to be normalise, so that's our second step. This is saying how many units we are moving on x and y on each frame render. We multiple a speed constant to our normalised vector so it moves faster. This multiplication we be you moving velocity.
var offset : Vector2 = target.transform.position - transform.position ; var normalize : Vector2 = offset.normalized; var moveVelocity : Vector2 = normalize * speed; rigidbody2D.velocity = moveVelocity;
So if any obstacle are between the Pateat and you, the monster will follow. The previous code show how we move the monster toward the player's position.