Search code examples
c#unity-game-engineunity3d-2dtools

Move gameobject to click position in unity 2d


Is it possible to move a gameobject to click position in unity 2D while gameobject is a rigidbody 2d with gravity and movement looks like jump from gameobject's position to click position. Any help reference will be really helpful :)


Solution

  • something a bit like this?

    Transform projectile;
    float speed = 5f;
    
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.z = projectile.position.z;
    
            Vector3 offset = target - projectile.position;
            Vector3 direction = offset.normalized;
            float power = offset.magnitude;
            projectile.GetComponent<RigidBody2D>().AddForce(direction * power * speed);
        }
    }