How can you realize the movement of monsters in Diablo. Namely, only on 8 sides (vertically, horizontally and diagonally) on mobile devices, where the control with the help of a joystick on the screen. The game is isometric, there are monster sprites on 8 sides. And that's the problem. The monster moves behind the character, for example, downwards, then the character shifts diagonally and until the deflection angle is sufficient, the monster will be directed downwards, and it will already be moving with an offset diagonal. And it is necessary as in Diablo, to strictly on 8 sides. For clarity, this is https://youtu.be/0aQnRBAMVqE

Monster Motion Script:

public class EnemyControl : MonoBehaviour { private Animator anim; // Use this for initialization void Start () { anim = this.GetComponent<Animator> (); } // Update is called once per frame void Update () { float input_x = GetComponent<Rigidbody2D>().velocity.x; float input_y = GetComponent<Rigidbody2D>().velocity.y; bool walkingEnemy = (Mathf.Abs(input_x) + Mathf.Abs(input_y)) > 0; anim.SetBool("walkingEnemy", walkingEnemy); if (walkingEnemy) { anim.SetFloat("x", input_x); anim.SetFloat("y", input_y); transform.position+=new Vector3(input_x, input_y, 0).normalized*Time.deltaTime; } } } 
  • The script of this monster would show better, but not video. Now we can only guess what your code is and how to fix it. - Sergey Rufanov
  • added monster script - MikhailChu

1 answer 1

You need to separate the x and y axes and for each choose the value from: 0, 0.5, 1 s +/- of course. To do this, you can use the following rounding function with precision

 public float Round(float value, float precision) { if (precision < float.Epsilon) return value; float modul = value % precision; float result = value - modul; if (result < 0) { if (-modul >= precision / 2) result -= precision; } else { if (modul >= precision / 2) result += precision; } return result; } 

then the calculation of the displacement along axes will look something like this:

 Vector2 velocity = GetComponent<Rigidbody2D>().velocity.normalized; float speed = GetComponent<Rigidbody2D>().velocity.magnitude; float input_x = velocity.x; float input_y = velocity.y; input_x = Round(input_x, 0.5f); input_y = Round(input_y, 0.5f); Vector2 move = (new Vectro2(input_x, input_y)).normalized * velocity.magnitude; 

well, then use move to get the values ​​of x and y, now you have a motion vector with an angle of 45 degrees.

  • the movement has not changed, i.e. at 45 degrees the movement is going, it was before, but with a smaller angle there is a simple shift without changing the position - MikhailChu
  • Share the source, try to help with debugging - KingPeas
  • Do you mean to put somewhere project? - MikhailChu 4:27 pm
  • Well, either a demo with an example, you can use the example of a ball and a cube so that you can test it - KingPeas
  • I posted a project - MikhailChu