_EagleOwle_

Grid hex cursor

Jun 24th, 2021 (edited)
178
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. private Vector3 offSet;
  2.     [SerializeField] private float cellSize = 1;
  3.     [SerializeField] private Vector3 roundPosition;
  4.     [SerializeField] private Vector3 cursorPosition;
  5.  
  6.     private void Update()
  7.     {
  8.         cursorPosition = GetCursorPosition();
  9.        
  10.         if((Round(cursorPosition.z, cellSize) % 2) == 0)//Проверка на четность
  11.         {
  12.             roundPosition = new Vector3(RoundFloor(cursorPosition.x, cellSize), cursorPosition.y, Round(cursorPosition.z, cellSize));
  13.             offSet = Vector3.right * 0.5f;
  14.         }
  15.         else
  16.         {
  17.             roundPosition = new Vector3(Round(cursorPosition.x, cellSize), cursorPosition.y, Round(cursorPosition.z, cellSize));
  18.             offSet = Vector3.zero;
  19.         }
  20.  
  21.         transform.position = roundPosition + offSet;
  22.     }
  23.  
  24.     public Vector3 GetCursorPosition()
  25.     {
  26.         Vector3 mouse = Input.mousePosition;
  27.         Ray castPoint = Camera.main.ScreenPointToRay(mouse);
  28.         RaycastHit hit;
  29.         if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
  30.         {
  31.             return hit.point;
  32.         }
  33.  
  34.         return Vector3.zero;
  35.     }
  36.  
  37.     private float Round(float position, float cellSize)
  38.     {
  39.         return Mathf.Round(position / cellSize) * cellSize;
  40.     }
  41.  
  42.     private float RoundFloor(float position, float cellSize)
  43.     {
  44.         return Mathf.Floor(position / cellSize) * cellSize;
  45.     }
  46.  
RAW Paste Data