Advertisement
Guest User

Untitled

a guest
Mar 24th, 2025
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | Gaming | 0 0
  1.  
  2. using UnityEngine;
  3.  
  4. public class DraggableBlock : MonoBehaviour
  5. {
  6. private bool isDragging = false;
  7. private Vector2 startPosition;
  8. private GridManager gridManager;
  9.  
  10. private void Start()
  11. {
  12. gridManager = FindObjectOfType<GridManager>();
  13.  
  14. if (gridManager == null)
  15. {
  16. Debug.LogError("❌ GridManager NOT found in the scene! Make sure GridManager exists.");
  17. }
  18. }
  19.  
  20. private void OnMouseDown()
  21. {
  22. startPosition = transform.position; // Store the original position
  23. isDragging = true;
  24. }
  25.  
  26. private void OnMouseDrag()
  27. {
  28. if (!isDragging) return;
  29.  
  30. Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  31. transform.position = mousePosition; // Move block with the mouse
  32. }
  33.  
  34. private void OnMouseUp()
  35. {
  36. isDragging = false;
  37.  
  38. if (gridManager == null)
  39. {
  40. Debug.LogError("❌ GridManager reference is missing!");
  41. return;
  42. }
  43.  
  44. Vector2 snappedPosition = gridManager.SnapToGrid(transform.position);
  45.  
  46. if (gridManager.IsCellEmpty(snappedPosition))
  47. {
  48. transform.position = snappedPosition;
  49. gridManager.PlaceBlock(snappedPosition, transform);
  50. Debug.Log($"✅ Block successfully placed at: {snappedPosition}");
  51. }
  52. else
  53. {
  54. Debug.LogWarning("⚠️ Invalid Placement: Returning to start position.");
  55. transform.position = startPosition;
  56. }
  57. }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement