How can I make something move without floating after I release the move key?
I'm new to Unity 5 and I've been trying to make a first project which is basically PONG, I got to the part where I want the player to move up when I press W, but the movement is floaty- the player continues to move abit after I release W.
public KeyCode moveUp;
public KeyCode moveDown;
Vector2 movespeed = new Vector2 ();
private Rigidbody2D rb;
void Start()
{
movespeed.x = 0;
rb = GetComponent<Rigidbody2D> ();
}
void Update ()
{
if (Input.GetKey (moveUp)) {
movespeed.y = 10;
rb.AddForce (movespeed);
}
else if (Input.GetKey (moveDown)) {
movespeed.y = -10;
rb.AddForce (movespeed);
}
else
{
movespeed.y = 0;
rb.AddForce (movespeed);
}
}
I tried accessing the velocity of RigidBody2D:
rb.velocity.y = 10;
But it seems to work only in Unity 4.
Is there any way to make the object stop when releasing the move key?
You are moving a physical object with forces. A physical object will never stop abruptly without a counterforce, because it is a slave of inertia.
Either apply a properly calculated counter-force to it when releasing the buttons, or change the approach from physical (rigidbodies and forces) to position-based (position.z += 1) for example.
Setting the rigidbody to kinematic and then enabling physics again on demand is a mis-use of the entire physics system, like $$anonymous$$elv$$anonymous$$ay explained already.
Answer by MelvMay · Apr 18, 2016 at 02:58 PM
rb.velocity.y = 10;
This is a C# issue, it won't work in Unity 4 either. Velocity is a Vector2 value-type so you cannot set an individual component of it. When accessing it, you get a copy of the value-type (they are passed by-value).
To do this, you need to set the velocity to a whole new Vector2 like so:
rb.velocity = new Vector2 (rb.velocity.x, 10.0f);
This is how C# works:
rb.velocity (returns a copy of the velocity Vector2)
rb.velocity.y = 10 (sets the Y of the copy of the velocity Vector2)
If you want to zero the velocity then you'd do this:
rb.velocity = new Vector2.zero;
Note that by applying force in the 'Update' callback, you're doing it per-frame therefore you'll get different forces and speeds depending on the frame-rate. You should do this in the 'FixedUpdate' callback.
Answer by M-Hanssen · Apr 18, 2016 at 02:39 PM
Set rigidbody to kinematic = true
when you want to make it stop completely.
Don't forget to switch to kinematic = false
when you move it again
Changing the body type like this is non-trivial and is a mis-use. It causes all contacts to be deleted and re-calculated during the next fixed-update.
Your answer
Follow this Question
Related Questions
i am making a pong game and it works fine till i reset the game 1 Answer
Random freezes during the game 0 Answers
Z position moving in 2D space 1 Answer
Rigidbody.AddForce and Time.TimeScale 1 Answer
I can't seem to rotate my character depending on what side he is running to (2D sidescroller) 0 Answers