Skip to content

Instantly share code, notes, and snippets.

@gegagome
Last active August 15, 2017 06:54
Show Gist options
  • Save gegagome/56379416596314ac677b5a92fee118eb to your computer and use it in GitHub Desktop.
Save gegagome/56379416596314ac677b5a92fee118eb to your computer and use it in GitHub Desktop.
using UnityEngine.EventSystems;
using UnityEngine;
public class Stem : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler
{
Vector3 _pos;
Vector3 _posOffset;
RectTransform _thisRectTransform;
RectTransform _parentRectTransform;
Rigidbody2D _rb;
void Awake() {
if (_rb == null) {
_rb = GetComponent<Rigidbody2D>();
}
Debug.Log(_rb);
Canvas canvas = GetComponentInParent<Canvas>();
if (canvas != null) {
_parentRectTransform = canvas.GetComponent<RectTransform>();
_thisRectTransform = GetComponent<RectTransform>();
Debug.Log("_parentRectTransform " + _parentRectTransform + " exists");
}
}
public void OnPointerDown(PointerEventData eventData) {
RectTransformUtility.ScreenPointToWorldPointInRectangle(_thisRectTransform,
eventData.position,
eventData.pressEventCamera,
out _posOffset);
}
public void OnPointerClick(PointerEventData eventData) {
}
// this method requires IBeginDragHandler
public void OnBeginDrag(PointerEventData eventData) {
}
// this method requires IDragHandler
public void OnDrag(PointerEventData eventData) {
if (_parentRectTransform == null)
{
return;
}
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(_thisRectTransform,
eventData.position,
eventData.pressEventCamera,
out _pos)) {
_rb.MovePosition(_pos);
}
}
// this method requires IEndDragHandler
public void OnEndDrag(PointerEventData eventData) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment