- Home /
Crashing issue related to changing velocity
What I'm trying to do is get an object's velocity to change with a smooth transition. The code is supposed to decrease the y-velocity by 0.1 each frame, until it reaches -2.5. However, whenever the code is executed, Unity freezes and becomes unresponsive. Does anyone know what the issue is?
void MoveDown() {
while (rb.velocity.y > -2.5) {
Vector2 newV;
newV.x = 0f;
newV.y = -.1f;
rb.velocity += newV;
}
}
Answer by MarioSantoso · Apr 15, 2018 at 04:06 AM
It is better to take out the while loop and do either of these to get what you want
Just add/increase drag in the rigidbody property. Your object will slow down automatically.
If for whatever reason you need to slowdown one of the axis only, do this
private void FixedUpdate() { _rb.velocity += new Vector3(-0.5f * Time.deltaTime, 0, 0); } // _rb is reference to the rigidbody // add this code to the script attached to the object you want to slow down // modify as you see fit
Answer by toddisarockstar · Apr 15, 2018 at 03:48 AM
while loops always freeze unity if the condition in the () brackets are never met. (while loops can cause endless loops )
possibly your velocity cant change. maybe its gameobject is against a collider or whatever.
if you wanted to write your code with the loop as you have it you could write it like this so the while loop is not dependent on the game engines condition.
void MoveDown() {
float y = rb.velocity.y ;
while (y > -2.5) { y=y-.1f; }
rb.velocity = new Vector3(rb.x,y,rb.z);
}
but really, i cant see what the loop is for. if you wanted to simply limit the y velocity why wouldn't you get the same effect saying:
if(rb.velocity>2.5f){rb.velocity = new Vector3(rb.velocity.x,2.5f,rb.velocity.z);}
Have you tested these code?
float y = rb.velocity.y ;
while (y > -2.5) { y=y-.1f; }
rb.velocity = new Vector3(rb.x,y,rb.z);
// You will not get gradual slowdown with this
if(rb.velocity>2.5f)
// Will throw error because velocity is a Vector3