# Add force to object at specific angle issue

Discussion in 'Scripting' started by allardkeij, Jul 14, 2018.

1. ### allardkeij

Joined:
Jun 2, 2018
Posts:
1
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:
Code (CSharp):
1. public void OnPointerUp(PointerEventData data)
2.     {
3.       float anglex = transform.position.x;
4.       float angley = transform.position.y;
5.
6.       float throwAngle = Mathf.Atan2(anglex - m_StartPos.x, angley - m_StartPos.y) * Mathf.Rad2Deg;
7.
8.         Vector3 dir = Quaternion.AngleAxis(throwAngle, Vector3.forward) * Vector3.right;
9.
11.
12.         Debug.Log(throwAngle);
13.
14.     }

2. ### Doug_B

Joined:
Jun 4, 2017
Posts:
1,406
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? :-
Code (CSharp):
1. public class Test : MonoBehaviour
2. {
3.     void Start()
4.     {
5.         m_body = GetComponent<Rigidbody>();
6.     }
7.
8.     void OnMouseDown()
9.     {
10.         if(!m_drag)
11.         {
12.             m_drag = true;
13.             m_began = Input.mousePosition;
14.         }
15.     }
16.
17.     void OnMouseUp()
18.     {
19.         if (m_drag)
20.         {
21.             var now = Input.mousePosition;
22.             m_body.AddForce((m_began - now).normalized * m_thrust);
23.             m_drag = false;
24.         }
25.     }
26.
27.     const float m_thrust = 2f;
28.     Rigidbody m_body;
29.     Vector3 m_began;
30.     bool m_drag;
31. }