MaskPainter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4. namespace SoftMasking.Samples {
  5. [RequireComponent(typeof(RectTransform))]
  6. public class MaskPainter : UIBehaviour, IPointerDownHandler, IDragHandler {
  7. public Graphic spot;
  8. public RectTransform stroke;
  9. RectTransform _rectTransform;
  10. protected override void Awake() {
  11. base.Awake();
  12. _rectTransform = GetComponent<RectTransform>();
  13. }
  14. protected override void Start() {
  15. base.Start();
  16. spot.enabled = false;
  17. }
  18. public void OnPointerDown(PointerEventData eventData) {
  19. UpdateStrokeByEvent(eventData);
  20. }
  21. public void OnDrag(PointerEventData eventData) {
  22. UpdateStrokeByEvent(eventData, drawTrail: true);
  23. }
  24. void UpdateStrokeByEvent(PointerEventData eventData, bool drawTrail = false) {
  25. UpdateStrokePosition(eventData.position, drawTrail);
  26. UpdateStrokeColor(eventData.button);
  27. }
  28. void UpdateStrokePosition(Vector2 screenPosition, bool drawTrail = false) {
  29. Vector2 localPosition;
  30. if (RectTransformUtility.ScreenPointToLocalPointInRectangle(_rectTransform, screenPosition, null, out localPosition)) {
  31. var prevPosition = stroke.anchoredPosition;
  32. stroke.anchoredPosition = localPosition;
  33. if (drawTrail)
  34. SetUpTrail(prevPosition);
  35. spot.enabled = true;
  36. }
  37. }
  38. void SetUpTrail(Vector2 prevPosition) {
  39. var movement = stroke.anchoredPosition - prevPosition;
  40. stroke.localRotation = Quaternion.AngleAxis(Mathf.Atan2(movement.y, movement.x) * Mathf.Rad2Deg, Vector3.forward);
  41. spot.rectTransform.offsetMin = new Vector2(-movement.magnitude, 0);
  42. }
  43. void UpdateStrokeColor(PointerEventData.InputButton pressedButton) {
  44. spot.materialForRendering.SetInt("_BlendOp",
  45. pressedButton == PointerEventData.InputButton.Left
  46. ? (int)UnityEngine.Rendering.BlendOp.Add
  47. : (int)UnityEngine.Rendering.BlendOp.ReverseSubtract);
  48. }
  49. }
  50. }