Maintaining object velociy via magnitude and Normalize not working

I am having an odd issue, I tried to use classic game programming code to maintain my ball velocity after tweeaking, like thus:
get velocity magnitude, save as “speed”
tweak velocity
normalize velocity
scale velocity back up by multiplying with speed

…but my ball takes off at lightspeed. I commented out the tweak, so theoretically it should just save magnitude as speed, normalize, then remultiply by speed back to original magnitude, but it STILL goes nuts. Why?
Here’s my actual code:

private void OnCollisionEnter2D(Collision2D collision)
    {
        if (hasStarted)
        {
            AudioClip clip = ballSounds[Random.Range(0, ballSounds.Length)];
            myAudioSource.PlayOneShot(clip);

            Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor),
            Random.Range(0f, randomFactor));            

            float speed = myRigidBody2D.velocity.magnitude;

            myRigidBody2D.velocity.Normalize();
            //myRigidBody2D.velocity += velocityTweak;
           // myRigidBody2D.velocity.Normalize();
            myRigidBody2D.velocity *= speed;
        }
    }

Hi Gibgezr,

Please log the variables into your console to see if they have the expected values.

After logging, it seems that this line:

myRigidBody2D.velocity.Normalize();

Is doing nothing. The magnitude of the vector is the same before and after that line of code.
Any idea why?

The Normalize() method returns a Vector3 object. You need to assign it to a variable, multiply that variable with speed and assign the variable to velocity.

Did this help?

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.