Search code examples
c#unity-game-engine2dphysics

How do I make a throwing (using drag) system for items in my 2D game?


I've looked near and far but I can't find a definitive answer to how I can do this. I'm using image GameObjects with dynamic Rigidbodies and 2D colliders. The dragging function works well but I can't get the items to fly off into the distance whenever you swipe the item. Here is my drag-and-drop code:

  [SerializeField] private Canvas canvas;
  private RectTransform rectTransform;
  private Rigidbody2D rigidbody;


  private void Awake() {
    rectTransform = GetComponent<RectTransform>();
    rigidbody = GetComponent<Rigidbody2D>();
  }

  public void OnBeginDrag(PointerEventData eventData) {
    rigidbody.gravityScale = 0;
  }

  public void OnDrag(PointerEventData eventData) {
    rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;

  }

  public void OnEndDrag(PointerEventData eventData) {
    rigidbody.gravityScale = 50;
  }

(sorry for the indent)

I tried this over and over with springs and stuff, and I thought it would throw the item across the screen when you swiped, but it either gives me irrelevant errors or makes no change. Please help!


Solution

  • SOLVED! Here's my full script. I'll comment anything that I've changed.

    [SerializeField] private Canvas canvas;
    private RectTransform rectTransform;
    private Rigidbody2D rigidbody2d;
    private SpringJoint2D _spring; // Just a reference to a spring
    
    private void Awake() {
      rectTransform = GetComponent<RectTransform>();
      rigidbody2d = GetComponent<Rigidbody2D>();
    
      _spring = GetComponent<SpringJoint2D>(); // Set the spring to the spring 
      //I put on my GameObject
      _spring.connectedAnchor = rectTransform.position; // Set the spring's 
      //connected anchor to my object's position
    }
    
    public void OnBeginDrag(PointerEventData eventData) {
       rigidbody2d.gravityScale = 0;
    
       _spring.enabled = true; // Enable the spring (to track movement)
    }
    
    public void OnDrag(PointerEventData eventData) {
    
       if(_spring.enabled == true) { // If the spring is on...
         Vector2 mousePos = Input.mousePosition; // ... Get the mouse position 
         in world coordinates ... 
         _spring.connectedAnchor = mousePos; // .... and set the spring's 
         connected anchor to the mousePos variable.
       }
    
     }
    
     public void OnEndDrag(PointerEventData eventData) {
       rigidbody2d.gravityScale = 50;
       _spring.enabled = false; // Disable the spring.
     }
    

    Here are my spring settings: Enable collision is false. No connected Rigidbodies. Don't auto-config connected anchor. anchor is 0, 0. (Don't worry about the connected anchor. It doesn't matter.) Auto-config distance is false. distance is 0.005 (minimum). Damping is 0. Frequency is 2. BF is infinity.

    And that's all!