Search Unity

Question How do I give an impulse to a game object in the direction of the cursor?

Discussion in '2D' started by Maksym_Pop, Nov 17, 2020.

  1. Maksym_Pop

    Maksym_Pop

    Joined:
    Jun 4, 2020
    Posts:
    6
    Hi!

    I don't know how do I give force to game object in the direction of the cursor!

    Now I do this:
    Code (CSharp):
    1. Vector 3 mouse =
    2. (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
    3.  
    And give force:
    Code (CSharp):
    1. public float force;
    2.  
    3. gameObject.GetComponent<Rigidbody2D>().velocity = (mouse * force);
    But in this case, the impact force will depend on how far the cursor is from the object. And I need it to be independent. In other words, the object always flies towards the cursor at the same speed, regardless of whether the cursor is close or far away.

    I tried doing this:
    Code (CSharp):
    1. Vector 3 mouse = (Camera.main.ScreenToWorldPoint(Input.mousePosition);
    That is, I did not withdraw my position. But then the object does not fly in the direction of the cursor, but for some reason a little to the side.

    Please help me!

    P.s. Sorry for the mistakes, I don't know much English.
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Last edited: Nov 17, 2020
    Maksym_Pop likes this.
  3. Maksym_Pop

    Maksym_Pop

    Joined:
    Jun 4, 2020
    Posts:
    6
    eses likes this.