- Home /
rigidbody 2d addfoce by vector math
Hello. Recently i've used a code to move objects by 3d addforce version. Raycasts from camera etc. Works beautifully. Now i'm coding 2d and have some troubles. I've removed raycasts, now i have a code like this:
public class MoveScript : MonoBehaviour
{
Vector2 initial_pos,released_pos;
Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void OnMouseDown()
{
initial_pos = Input.mousePosition;
}
void OnMouseOver()
{
released_pos = Input.mousePosition;
}
void OnMouseExit()
{
Vector2 fire_vector = released_pos-initial_pos;
rb.AddForce(fire_vector);
}
}
Well, it's simple enought and i have 2d vectors according to debug information, but it works.. strange. Similar code for Vector3 variables, as i said before, works great. What did i misunderstand? Do i need to translate Mouse.Position into some screen coordinates?
Well, had to came back to raycast functions. For example:
void On$$anonymous$$ouseDown() { RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); initial_pos = hit.point; }
Still do not understand why similar coordinates that input.$$anonymous$$ouse returns doesn't give me the similar direction and the lenght of the vector but seems like it's my education problem, not the Uinty's :).
Your answer
![](https://koobas.hobune.stream/wayback/20220613192423im_/https://answers.unity.com/themes/thub/images/avi.jpg)