0

I'm new to C# and Unity. I need to normalize the velocity of my player, but only in the x-direction. My current code is

void Update ()
{
if(rb2d.velocity.magnitude > maxSpeed)
    {
        rb2d.velocity = rb2d.velocity.normalized * maxSpeed;
    }

This controls all velocity. I tried

void Update ()
{
if(rb2d.velocity.x.magnitude > maxSpeed)
    {
        rb2d.velocity.x = rb2d.velocity.x.normalized * maxSpeed;
    }

But I think this was removed in Unity 5. What can I do?

2
  • i don't know much about unity, but i do know maths. You can normalize a vector by dividing the x and y components by the length of the vector Commented Apr 19, 2018 at 15:12
  • I tried that, but that's not really the issue, mainly because the max speed is the issue. But thanks Commented Apr 19, 2018 at 15:14

1 Answer 1

2

Just divide your velocity X by the velocity's magnitude, which is essentially what normalize does.

// Make a copy of the current velocity.
Vector2 velocity = rb2d.velocity;

// Divide the x component by magnitude, equivalent to normalizing it.
velocity.x = velocity.x / velocity.magnitude;

// velocity now only has its x component normalized and y untouched
rb2d.velocity = velocity * maxSpeed;
Sign up to request clarification or add additional context in comments.

2 Comments

I don't fully understand how I can implement this. I put that in the if statement. and it's saying XVelocity doesn't exist in current context.
@Zanolon well, XVelocity doesn't exist in this answer either, so it's clearly something you added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.