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?
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.
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