- Home /
how come object is moving when i pressed nothing?
Please some one explain me how my object is moving when i set movement to 0 and if statement clearly states that rigidbody2d shouldn't move when movement = 0. but when i run program ball move due to gravity even with movement is zero.. please someone explain this i have spent 2 hour on this problem and now my brain is staring to hurt
public class Controller : MonoBehaviour {
public float movement=0;
public float speed = 6;
private Rigidbody2D RD;
// Use this for initialization
void Start () {
RD = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
if(movement>0)
{ RD.velocity = new Vector2(movement*speed,RD.velocity.y); }
else if(movement<0)
{ RD.velocity = new Vector2(movement * speed, RD.velocity.y); }
}
}
Answer by _samuel12345 · May 26, 2018 at 05:42 PM
You are only changing the velocity if movement is less than or greater than 0 - not equal to it. Try:
else if(movement == 0){
RD.velocity = Vector2.zero;
}
i am not asking for solution i am asking "why object is moving when the required condition is not satisfied"?
Like @_samuel12345 explained, you have never said that if the movement is 0 the object must NOT move. So if gravity is on the object will go downwards.
so object will move regardless of object.velocity because far as i know velocity make object move. so having movement==0 means object should move automatically. Is this some built in functionality into unity?
Answer by Tobychappell · May 26, 2018 at 09:37 PM
Just tested your code and yes it doesn't set the velocity when movement = 0.
But if movement was equal to 10 and you hit play, the code will constantly set the velocity to (10,0).
The rigidbody will then move in the direction (10,0).
Whilst still in play mode.. you then set movement to 0....
The rigidbody will still move as its velocity is still (10,0).
The reason for this is because nothing else is acting on it, your code is't telling it to stop moving when movement = 0. Think of it drifting in space, if you push on something it will remain travelling at the speed that it was at when it left contact from your hand. Im assuming your linear drag is 0 (which is default when you create a Rigidbody2D) so the physics engine wont even be slowing it down.