# Make enemy move diagonally in 2D

I'm making the enemy follow the player only straight or diagonally e.g.(1,1)(1,0)(0,1)(-1,1). I expected the problem that I have, but I don't really know how to fix it. When my enemy is placed diagonally (relative to the player but not exactly), It will alternate rapidly between going diagonally and straight, causing it to appear like its vibrating.

here is the simple script returning the Vector2 to follow:

        Vector2 direction = (player.position - goblinTr.position).normalized;
direction.x = Mathf.Round(direction.x);
direction.y = Mathf.Round(direction.y);

return direction;

• Is this calculation performed on every pass through the game loop? Apr 1, 2021 at 1:25

So I figured out a solution. I basically check the previous direction I got from my function (without rounding it) and check the angle with the new direction my sprite wants to go (without rounding it) by doing Vector3.Angle(previousVector,direction) and then verify if the angle is greater than 30. If it is, I change the direction. If not, I keep the previous direction.

Vector2 direction = (player.position - goblinTr.position).normalized;

if (Vector3.Angle(previousVec, direction) >= minVariation || previousVec == Vector2.zero)
{
var = Vector3.Angle(previousVec, direction);
previousVec = direction;
direction.x = Mathf.Round(direction.x);
direction.y = Mathf.Round(direction.y);

return direction;
}
else
{
previousVec.x = Mathf.Round(previousVec.x);
previousVec.y = Mathf.Round(previousVec.y);

return previousVec;
}

• nice problem solving! Apr 1, 2021 at 21:44