# Normalizing a Vector

*Click or tap to place vector*

## Description

Normalizing a vector means to transform a vector such that the resulting vector is oriented in the same direction, but has a length of 1. This is done by finding the length of the original vector, and dividing each component of the vector by that length.

A common application of normalizing a vector is finding the coordinates of specified distances along a known direction. In a first-person shooter video game, this could be finding the coodinates of a rocket for each frame as it travels along the direction the weapon was pointed. The weapon's direction would be represented as a vector. The vector would then be normalized to unit length (a length of 1). This unit vector could then be scaled by multiplying it by the speed of the rocket (distance per frame). Moving the rocket the next frame would then be as simple as adding this scaled vector to the rocket's current location.

## Javascript

function normalize(v)
{
var w = {x: v.x, y: v.y}; // Copy v so we don't alter the original reference
var length = Math.sqrt(w.x * w.x + w.y * w.y);
w.x /= length;
w.y /= length;
return w;
}

## Example from Half-Life (C++)

```
int CLeech::TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType )
{
pev->velocity = g_vecZero;
// Nudge the leech away from the damage
if ( pevInflictor )
{
pev->velocity = (pev->origin - pevInflictor->origin).Normalize() * 25;
}
return CBaseMonster::TakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
}
```

This C++ code from Half-Life(1998) is responsible for applying damage to an NPC known as the leech. It establishes the direction the damage came from by creating a vector starting from the source of the damage and pointing toward the leech. This vector is then normalized and scaled up by 25 units and then set as the leech's velocity vector. In effect, it pushes the leech in the opposite direction as the source of the damage.