why doesn’t this code work
if (rb.velocity.x > 5)
{
rb.velocity.Set(5, rb.velocity.y);
}
if (rb.velocity.x < -5)
{
rb.velocity.Set(-5, rb.velocity.y);
}
why doesn’t this code work
if (rb.velocity.x > 5)
{
rb.velocity.Set(5, rb.velocity.y);
}
if (rb.velocity.x < -5)
{
rb.velocity.Set(-5, rb.velocity.y);
}
This is a C# thing not a 2D thing.
When you access a value-type such as Vector2 above (.velocity) you get a copy of it. In C# this is what value-types are; they are passed around by value. Unlike reference types such as classes that “point” to the objects.
Above, when you read the velocity (Vector2), you have a copy of the velocity. The Vector2 has a Set method which you use to change your copy which is then lost because it’s not assigned back to where you read the value. This isn’t a problem with 2D physics or Unity. You just need to be careful when using value-types.
var velocity = rb.velocity;
if (velocity.x > 5)
{
rb.velocity = new Vector2(5, velocity.y);
}
else if (velocity.x < -5)
{
rb.velocity = new Vector2(-5, velocity.y);
}
A shorter version would be:
var velocity = rb.velocity;
rb.velocity = new Vector2(Mathf.Clamp(velocity.x, -5f, 5f), velocity.y);
NOTE: Above I read the velocity once and write it once. This isn’t related to your problem but I do this because it’s quicker as I’m not reading from the engine multiple times just to check parts of the velocity. Not much quicker here but the less work you do, the more time you have for other cool stuff to happen.
Thanks a lot!