Add force to object at specific angle issue

Hey guys i recently started with Unity (and C#) and i am trying to pull of a specific drag and shoot mechanism.

As i am figuring it out i am simply to unknown with the whole world axis and i’m not very good with math.

Therefore i can’t figure this one out on my own.

The idea is simple. My object is located in a 3D world and i’ve put in a Joystick. When i drag and release the joystick my “player” object should be shot at the opposite angle. I am trying to do that with a AddForce function.

I do get some results but they are far from what it should be.

To calculate the angle i am using the start point of the joystick ( dead center ) and the position when it’s released.

What i think is happening is that my object actually flies in a 3D world while i am trying to let it shoot “2D” style a.k.a. 360 degrees on the x and y axis not on the Z. I simply locked the Z axis on my object.

Long story short, applying a force to my object with the joystick works fine but the angles don’t really work out like they should.

This is my code so far:

public void OnPointerUp(PointerEventData data)
    {
      float anglex = transform.position.x;
      float angley = transform.position.y;
 
      float throwAngle = Mathf.Atan2(anglex - m_StartPos.x, angley - m_StartPos.y) * Mathf.Rad2Deg;
 
        Vector3 dir = Quaternion.AngleAxis(throwAngle, Vector3.forward) * Vector3.right;
 
        dagger.GetComponent<Rigidbody>().AddForce(dir * thrust);
 
        Debug.Log(throwAngle);
             
    }

I have just tried doing this using the mouse. The Z axis takes care of itself as the mouse cannot move along that plane.

Here is the code. If I understand your requirement correctly, I think it is along the lines you are wanting. Maybe it can help give you some ideas? :-

public class Test : MonoBehaviour
{
    void Start()
    {
        m_body = GetComponent<Rigidbody>();
    }

    void OnMouseDown()
    {
        if(!m_drag)
        {
            m_drag = true;
            m_began = Input.mousePosition;
        }
    }

    void OnMouseUp()
    {
        if (m_drag)
        {
            var now = Input.mousePosition;
            m_body.AddForce((m_began - now).normalized * m_thrust);
            m_drag = false;
        }
    }

    const float m_thrust = 2f;
    Rigidbody m_body;
    Vector3 m_began;
    bool m_drag;
}