0
\$\begingroup\$

In Unity 5 I have an object move when I press a button, force is added as seen by the code below. Then once this force is added I print out its velocity. The problem is that in the console my first print out with the first button press is "velocity(0.0,0.0)" then the second button press gives the printout "velocity(2.0,0.0)". Why is it that i get a velocity of 0 on the first button press even though my object is moving on the screen?

if (isPressed == true) {
            moveableBarrel.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (100, 0));

            Debug.Log ("velocity" + moveableBarrel.GetComponent<Rigidbody2D> ().velocity);

            isPressed = false;
        }

Edit **Incase anyone else asks, the code is within a FixedUpdate Method

\$\endgroup\$
3
  • \$\begingroup\$ Try putting this code in FixedUpdate() instead of Update(). More than likely, you are just playing catch-up with your physics engine. \$\endgroup\$
    – jgallant
    Sep 15, 2015 at 14:54
  • \$\begingroup\$ @Jon this code is already within FixedUpdate :( would it still be trying to catchup? \$\endgroup\$
    – CH99
    Sep 15, 2015 at 15:04
  • 1
    \$\begingroup\$ Yeah, I am re-reading what I posted, and I regardless I would be wrong here. My guess is, that the physics engine calculates all the forces applied, and then updates its velocity at each tick (which is probably done in the background out of your control, after the FixedUpdate() is called). The documentation doesn't really specify how the behaviour works, therefore, I would assume this is how it does work. \$\endgroup\$
    – jgallant
    Sep 15, 2015 at 15:06

1 Answer 1

2
\$\begingroup\$

You are changing its velocity using the AddForce method. This adds a force, not a velocity to the body. The change of velocity happens the next time the rigidbody physics are processed by the game engine, which happens during the next FixedUpdate.

\$\endgroup\$
1
  • \$\begingroup\$ thanks for this! had a suspicion it was something like that, ty! \$\endgroup\$
    – CH99
    Sep 17, 2015 at 9:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .