Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.EventSystems;
- namespace Levels.Logic
- {
- public class DragPhysics2DObjectVer2 : MonoBehaviour, IDragHandler, IEndDragHandler
- {
- [SerializeField] private Camera _camera;
- [SerializeField] private Rigidbody2D _rigidbody2D = null;
- [SerializeField] private float _velocityMultiplier = 10f;
- [SerializeField] private bool _otherRigidbody;
- [SerializeField] private MoveType _moveType = MoveType.XY;
- [SerializeField] private bool _isFreezePositionWhenNotMoved = false;
- private Vector3 _previousDragPosition;
- private Vector2 _direction;
- private Vector3 _currentDragPosition;
- private Vector2 _newPosition;
- private bool _isCanDrag = true;
- private bool _isCanMove = false;
- private Vector2 _offset;
- private bool _isInput = false;
- private bool _isClickOnObject = false;
- private RigidbodyConstraints2D _previousConstraint;
- public bool IsClickOnObject => _isClickOnObject;
- public bool IsCanDrag
- {
- get => _isCanDrag;
- set => _isCanDrag = value;
- }
- public Rigidbody2D Rigidbody2D => _otherRigidbody
- ? _rigidbody2D
- : _rigidbody2D != null && ReferenceEquals(_rigidbody2D.gameObject, gameObject)
- ? _rigidbody2D
- : _rigidbody2D = GetComponent<Rigidbody2D>();
- public Camera Camera => _camera != null ? _camera : _camera = Camera.main;
- #if UNITY_EDITOR
- private void OnValidate()
- {
- var rigidbody2D1 = Rigidbody2D;
- var camera1 = Camera;
- }
- #endif
- private void Awake()
- {
- var camera1 = Camera;
- IsCanDrag = true;
- _previousConstraint = Rigidbody2D.constraints;
- }
- public void OnDrag(PointerEventData eventData)
- {
- if (IsCanDrag == false)
- {
- Rigidbody2D.velocity = Vector2.zero;
- return;
- }
- var screenToWorldPoint = (Vector2) Camera.ScreenToWorldPoint(eventData.position);
- Rigidbody2D.velocity = (screenToWorldPoint - (Rigidbody2D.position + _offset)) * _velocityMultiplier;
- }
- public void OnEndDrag(PointerEventData eventData)
- {
- Rigidbody2D.velocity = Vector2.zero;
- }
- private enum MoveType
- {
- XY,
- X,
- Y,
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement