Advertisement
wasdswag

vita AI Movement

Dec 21st, 2019
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.70 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class createTiles : MonoBehaviour
  7. {
  8.     GameObject tile;
  9.     bool black;
  10.     GameObject currentActor;
  11.     bool diagonalMode;
  12.     GameObject currentTile;
  13.  
  14.  
  15.     public List<Vector3> possibleSteps = new List<Vector3>();
  16.  
  17.     public Text text;
  18.  
  19.     public int step = 3;
  20.     bool allow;
  21.     public Transform player;
  22.     bool correct;
  23.     public int width, height;
  24.  
  25.  
  26.     void Start()
  27.     {
  28.         // пока просто ровное поле шахматное 20x20
  29.         for (int x = -width; x < width; x++)
  30.         {
  31.             black = !black;
  32.             for (int z = -height; z < height; z++)
  33.             {
  34.                 tile = Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), new Vector3(x, 0, z), Quaternion.identity);
  35.                 tile.GetComponent<Renderer>().material.color = black ? Color.gray : Color.white;
  36.                 black = !black;
  37.                 tile.transform.parent = transform;
  38.             }
  39.  
  40.         }
  41.  
  42.     }
  43.  
  44.     Vector3 FindNearest(float y)
  45.     {
  46.         // очень большое число
  47.         Vector3 nearby = Vector3.zero;
  48.         float d = Mathf.Infinity;
  49.  
  50.         for (int i = 0; i < possibleSteps.Count; i++)
  51.         {
  52.             // считаем дист до всех зверей
  53.             float dist = Vector3.Distance(player.position, possibleSteps[i]);
  54.  
  55.             // если дист меньше очень большого числа (d), делаем d равным этой дистанции
  56.             // поскольку это продолжающийся цикл, таким способом мы найдем самую небольшую дистанцию
  57.  
  58.             if (dist < d)
  59.             {
  60.                 nearby = new Vector3(possibleSteps[i].x, y, possibleSteps[i].z);
  61.                 d = dist;
  62.             }
  63.         }
  64.         //  возвращаем ближайшего
  65.         return nearby;
  66.  
  67.     }
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.     void Update()
  76.     {
  77.  
  78.         // делаем лучик
  79.         Vector3 pos = Input.mousePosition;
  80.         Ray ray = Camera.main.ScreenPointToRay(pos);
  81.         RaycastHit hit;
  82.  
  83.  
  84.         if (Physics.Raycast(ray, out hit, 100f))
  85.         {
  86.             if (hit.collider.CompareTag("Player") && Input.GetMouseButtonDown(0))
  87.             {
  88.                 Debug.Log(hit.collider.name);
  89.                 currentActor = hit.collider.gameObject;
  90.  
  91.             }
  92.  
  93.             if (currentActor != null)
  94.             {
  95.  
  96.                 if (hit.collider.tag != "Player")
  97.                 {
  98.                     currentTile = hit.collider.gameObject;
  99.                 }
  100.  
  101.                 Vector3 heading = hit.collider.transform.position - currentActor.transform.position;
  102.                 var distance = heading.magnitude;
  103.               // text.text = Mathf.Floor(distance).ToString();
  104.                 var direction = heading / distance;
  105.  
  106.                 // Vector3.Dot это разница направлений от -1 до 1
  107.                 // мы сравниваем два напрвления актора вперед и вправо с тайлом
  108.                 // (d и d2) игнорируем отрицаиельные числа через Mathf.Abs (все равно прямая или диагональ сзади или спереди)
  109.                 // если режим Вперед и d или d2 равны 0 добро перемещаться в этот тайл
  110.                 // ecли режим Диагональ и d = d2 значит тоже добро
  111.                 // d и d2 всегда число от 0,0 до 1,0
  112.  
  113.                 float d = Mathf.Abs(Vector3.Dot(direction, currentActor.transform.forward));
  114.                 float d2 = Mathf.Abs(Vector3.Dot(direction, currentActor.transform.right));
  115.  
  116.  
  117.                 int Mode = currentActor.GetComponent<ActorBehaviour>().walkingType;
  118.                 diagonalMode = Mode > 0; // если walkingType у актора 1 значит он должен ходить по диагонали, если 0 прямо
  119.  
  120.                 bool diagonal = (d - d2) < 0.01f && (d - d2) > -0.01f; // чтобы разрешить ход, если диагональный режим
  121.                 bool straight = d < 0.01f || d2 < 0.01f;
  122.  
  123.                 bool correctWay = diagonalMode ? diagonal : straight;
  124.  
  125.                 if (diagonal) // ecли оба одинаковы это диагональ
  126.                     Debug.LogWarning("DIAGONAL");
  127.                 else
  128.                     Debug.LogWarning("STRAIGHT");
  129.  
  130.  
  131.  
  132.  
  133.  
  134.                 if (Input.GetMouseButtonDown(0))
  135.                 {
  136.  
  137.                     allow = false;
  138.                     possibleSteps = new List<Vector3>();
  139.  
  140.                     for (int x = -step; x <= step; x++)
  141.                     {
  142.                         for (int z = -step; z <= step + 1; z++)
  143.                         {
  144.                             Vector3 posPos = new Vector3(currentActor.transform.position.x + x, currentActor.transform.position.y,
  145.                                                          currentActor.transform.position.z + z);
  146.  
  147.                             Vector3 h = posPos - currentActor.transform.position;
  148.                             var dist = h.magnitude;
  149.                             var dir = h / dist;
  150.  
  151.                             float pd = Mathf.Abs(Vector3.Dot(dir, currentActor.transform.forward));
  152.                             float pd2 = Mathf.Abs(Vector3.Dot(dir, currentActor.transform.right));
  153.  
  154.                            
  155.  
  156.                             bool diag = (pd - pd2) < 0.01f && (pd - pd2) > -0.01f; // чтобы разрешить ход, если диагональный режим
  157.                             bool str = pd < 0.01f || pd2 < 0.01f;
  158.  
  159.                             correct = diagonalMode ? diag : str;
  160.  
  161.                             if (correct)
  162.                             {
  163.                                 possibleSteps.Add(posPos);
  164.                                 Debug.Log("forward: " + pd + "  right: " + pd2);
  165.                                 //Instantiate(GameObject.CreatePrimitive(PrimitiveType.Sphere), posPos, Quaternion.identity);
  166.                             }
  167.                         }
  168.                     }
  169.                     allow = true;
  170.  
  171.                 }
  172.  
  173.  
  174.                 if (Input.GetKeyDown(KeyCode.A) && allow)
  175.                 {
  176.                     currentActor.GetComponent<ActorBehaviour>().Target = FindNearest(currentActor.transform.position.y);
  177.                     allow = false;
  178.  
  179.                 }
  180.  
  181.            
  182.  
  183.             }
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.         }
  193.  
  194.     }
  195. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement