Search Unity

  1. Check out the Unite LA keynote for updates on the Visual Effect Editor, the FPS Sample, ECS, Unity for Film and more! Watch it now!
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

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:
    1,221
    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 at 11:36 AM
  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:
    1,221
    Oh! Dumb mistake, thanks! I'm editing the original post.