0
\$\begingroup\$

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.

enter image description here

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;
\$\endgroup\$
1
  • \$\begingroup\$ Is this calculation performed on every pass through the game loop? \$\endgroup\$
    – Pikalek
    Commented Apr 1, 2021 at 1:25

1 Answer 1

2
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ nice problem solving! \$\endgroup\$
    – Millard
    Commented Apr 1, 2021 at 21:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .