I'm using a rigibody2D on a cube in Unity. I have a constant force been added to slowly increase the speed and couple of ifs to cap it out if max speed is reached. This works but every now and then before fixed update the velocity randomly goes to zero. In addition at the time when it drops to zero it goes to some random numbers for a couple of frames (for example -5.453111E-16)
float horizontalAxis = Input.GetAxis("Horizontal"); //gets horizontal axis
Debug.Log("axis: " + Vector2.right * horizontalAxis * speed);
Debug.Log("velocity.x before addforce: " + rb2d.velocity.x);
rb2d.AddForce(Vector2.right * horizontalAxis * speed); //adds x force based on input and speed property
Debug.Log("velocity.x after addforce: " + rb2d.velocity.x);
//cap out speed to max if more than max (abs)
if(rb2d.velocity.x > maxSpeed)
Debug.Log("velocity.x over max: " + rb2d.velocity.x);
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
Debug.Log("capped velocity.x: " + rb2d.velocity.x);
if (rb2d.velocity.x < -maxSpeed)
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
Image of player components:
Answer by hexagonius
Dec 17, 2015 at 11:35 PM
I think it has to do with negating the scale on direction change, which might be bad in your, but is bad in a second case. instead of scaling the transform, put the visual as child object and ROTATE it around y axis. This might solve your problem as well as not break batching.
Nope, even if I comment out that part it still drops down to zero. In addition if I release the input and then press it again still doesnt move.
Answer by fosmark13
Apr 20 at 06:52 PM
hi, i now that is an old topic but i have the same problem with my character, it suddenly began to have this behaviour where its rigibody2d drops its y speed to zero without any reason , so the cuestion is... did you solve it?? and how?? i been searching for all the internet without a clear answer
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
5 People are following this question.
how to: Velocity or addForce to 2D (Instantiated?) Object
Sphere with AddForce or Velocity not moving
Keep gravity while adding velocity to a Rigidbody?
Instantiate GameObject with Velocity
How do I ignore gravity when using Rigidbody and always have the same jump force?