Advertisement
TwinFrame

CubeField

Mar 26th, 2023
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. using UnityEngine.InputSystem;
  6.  
  7. [RequireComponent(typeof(BoxCollider))]
  8.  
  9. public class CubeField : MonoBehaviour
  10. {
  11.     [SerializeField] private LayerMask _fieldMask;
  12.  
  13.     private BoxCollider _fieldCollider;
  14.     private bool _isEnterField = false;
  15.  
  16.  
  17.     public UnityAction EnterFieldEvent;
  18.     public UnityAction ExitFieldEvent;
  19.  
  20.     private void Awake()
  21.     {
  22.         _fieldCollider = GetComponent<BoxCollider>();
  23.     }
  24.  
  25.     private void FixedUpdate()
  26.     {
  27.         if (TryGetHitInField(Mouse.current.position.ReadValue(), Camera.main))
  28.         {
  29.             if (_isEnterField == false)
  30.             {
  31.                 _isEnterField = true;
  32.  
  33.                 EnterFieldEvent?.Invoke();
  34.             }
  35.         }
  36.         else
  37.         {
  38.             if (_isEnterField)
  39.             {
  40.                 _isEnterField = false;
  41.  
  42.                 ExitFieldEvent?.Invoke();
  43.             }
  44.         }
  45.     }
  46.  
  47.     private bool TryGetHitInField(Vector3 screenPosition, Camera camera)
  48.     {
  49.         Ray ray = camera.ScreenPointToRay(screenPosition);
  50.  
  51.         if (Physics.Raycast(ray, float.MaxValue, _fieldMask))
  52.             return true;
  53.         else
  54.             return false;
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement