Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to Normalize a Vector?

Tags:

c#

xna

I am learning XNA and in almost all of the educational kits found on http://creators.xna.com/en-US/. I always see a call to Normalize() on a vector. I understand that normalize basically converts the vector into unit length, so all it gives is direction.

Now my question is When to normalize and what exactly does it help me in. I am doing 2D programming so please explain in 2D concepts and not 3D.

EDIT: Here is code in the XNA kit, so why is the Normalize being called?

if (currentKeyboardState.IsKeyDown(Keys.Left) ||
            currentGamePadState.DPad.Left == ButtonState.Pressed)
        {
            catMovement.X -= 1.0f;
        }
        if (currentKeyboardState.IsKeyDown(Keys.Right) ||
            currentGamePadState.DPad.Right == ButtonState.Pressed)
        {
            catMovement.X += 1.0f;
        }
        if (currentKeyboardState.IsKeyDown(Keys.Up) ||
            currentGamePadState.DPad.Up == ButtonState.Pressed)
        {
            catMovement.Y -= 1.0f;
        }
        if (currentKeyboardState.IsKeyDown(Keys.Down) ||
            currentGamePadState.DPad.Down == ButtonState.Pressed)
        {
            catMovement.Y += 1.0f;
        }


        float smoothStop = 1;


        if (catMovement != Vector2.Zero)
        {
            catMovement.Normalize();
        }

        catPosition += catMovement * 10* smoothStop;

}

like image 533
Mike Diaz Avatar asked Jun 21 '10 00:06

Mike Diaz


2 Answers

In your example, the keyboard presses give you movement in X or Y, or both. In the case of both X and Y, as when you press right and down at the same time, your movement is diagonal. But where movement just in X or Y alone gives you a vector of length 1, the diagonal vector is longer than one. That is, about 1.4 (the square root of 2).

Without normalizing the movement vector, then diagonal movement would be faster than just X or Y movement. With normalizing, the speed is the same in all 8 directions, which I guess is what the game calls for.

like image 156
Detmar Avatar answered Oct 20 '22 00:10

Detmar


One common use case of vector normalization when you need to move something by a number of units in a direction. For example, if you have a game where an entity A moves towards an entity B at a speed of 5 units/second, you'll get the vector from A to B (which is B - A), you'll normalize it so you only keep the direction toward the entity B from A's viewpoint, and then you'll multiply it by 5 units/second. The resulting vector will be the velocity of A and you can then simply multiply it by the elapsed time to get the displacement by which you can move the object.

like image 23
Trillian Avatar answered Oct 19 '22 23:10

Trillian