Search code examples
androidunity-game-engine2d-games

Unity Android Drag Aim Release


I need help with (what I believe to be simple but I don't know) something (for android): I have a 2D ball, that is on a simple square table (you see it from above so I don't need gravity), I want to drag from that ball and release and upon release the ball goes in that direction or in opposite direction if you drag "behind" the ball. Just put your finger on the ball then drag and release. I searched for 2 days on forums and youtube and everywhere but I couldn't find what I need. I found something but it's really outdated and does not help me. Thank you for your help! And I am sorry for taking your time if there is already something answered that I didn't find!


Solution

  • This assumes you have a Rigidbody2D and collider attached to your ball and will launch the ball in the opposite direction that you drag.

    Rigidbody2D rbody;
    Vector2 startpos;
    Vector2 endpos;
    float power = 5f; // power of shot
    
    void Start()
    {
        rbody = GetComponent<Rigidbody2D>();
    }
    
    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            endpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            LaunchBall();
        }
    }
    
    void OnMouseDown()
    {
        startpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    
    void LaunchBall()
    {
        Vector2 direction = (startpos - endpos).normalized; // swap subtraction to switch direction of launch
        rbody.AddForce(direction * power, ForceMode2D.Impulse);
    }