Alex Rivera | Logout

When to Normalize a Vector?

Asked 2010-06-21T00:38:29.437
9

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;
Edit
Report

1 Answer

11

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.

answered 2010-06-21T02:32:34.470

Your Answer