Search Unity

How to apply a one-time (initial) impulse force

Discussion in 'Physics' started by Smkore_Kw4ard, Dec 20, 2017.

  1. Smkore_Kw4ard

    Smkore_Kw4ard

    Joined:
    May 2, 2017
    Posts:
    1
    I know how to use the
    Code (CSharp):
    1. GetComponent<Rigidbody>().AddForce();
    function. But to apply a one-time initial impulse, do I put this line in
    Code (CSharp):
    1. void start()
    or
    Code (CSharp):
    1. void update()
    ?
     
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,512
    I'd try something like this:
    Code (CSharp):
    1. public Vector3 impulse = new Vector3(5.0f, 0.0f, 0.0f);
    2.  
    3. bool m_oneTime = false;
    4.  
    5. void FixedUpdate ()
    6.     {
    7.     if (!m_oneTime)
    8.         {
    9.         GetComponent<Rigidbody>().AddForce(impulse, ForceMode.Impulse);
    10.         m_oneTime = false;
    11.         }
    12.     }
    Remember that the impuse is velocity multiplied by mass. If you want to give the object an initial velocity regardless it mass, use ForceMode.VelocityChange as second parameter to AddForce.
     
    Last edited: Nov 9, 2018
  3. Tom1962

    Tom1962

    Joined:
    Sep 19, 2018
    Posts:
    1
    Just some minor fixes to the above code.

    public class ImpulseForce : MonoBehaviour {
    //Give it a momentary force of 5 in the X direction but you can change this in unity to apply
    //an impulse force in any direction.
    public Vector3 impulseMagnitude = new Vector3(5.0f, 0.0f, 0.0f);

    bool m_oneTime = true;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
    if (m_oneTime)
    {
    GetComponent<Rigidbody>().AddForce(impulseMagnitude, ForceMode.Impulse);
    m_oneTime = false;
    Debug.Log("Here");
    }
    }
    }
     
  4. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,512
    Oh! Dumb mistake, thanks! I'm editing the original post.