# TikZ: Draw a unit vector

I have a two point p1 and p2:

  \node (p1) at (-1,-2) [point, label = {left:$P_1$}]{};
\node (p2) at (3, 4) [point, label = {below:$P_2$}]{};


How to draw a unit vector beginning at the point p1 and directed to a point p2 using only the variables p1 and p2?

• By normalizing it.
– c.p.
Dec 4, 2014 at 12:44
• Don't use \node to define \coordinate... Dec 4, 2014 at 13:23

You can use the calc library syntax with units. If you omit the unit it is understood as the full path percentage. Otherwise, depending on the unit that distance is traveled.

\documentclass[tikz]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[point/.style={circle,draw,inner sep=2pt}]
\node[point, label = {left:$P_1$}] (p1) at (-1,-2) {};
\node[point, label = {below:$P_2$}] (p2) at (3, 4) {};

\foreach \x[count=\xi] in {,mm,cm,in}{
\draw[opacity=1/\xi,line width=\xi pt] (p1) -- ($(p1)!1\x!(p2)$);% 1,1mm,1cm,1in respectively
}
\end{tikzpicture}
\end{document} • p1 is not p1.center... Dec 4, 2014 at 13:22
• Ok, but how to get distance between points p1 and p2? Dec 4, 2014 at 13:30
• @user67420 Search for veclen in pgfmanual.
– user11232
Dec 4, 2014 at 13:53
• @user67420 You want a unit vector why do you need the distance? You just need to specify the 1<unit> Dec 4, 2014 at 14:39
• @PaulGaborit True, but it is for example. You just need either (p2) for the finish or ($(p1)!0!(p2)$) for the start to make things equal for the full path. Dec 4, 2014 at 14:41

This draws the lines by a fraction of the distance between p1 and p1. For example 20% of the distance between p1 and p2:

\documentclass[tikz]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[point/.style={circle,draw,inner sep=2pt}]
\node[coordinate, label = {left:$P_1$}] (p1) at (-1,-2){};
\node[coordinate, label = {below right:$P_2$}] (p2) at (3, 4){};
\node[point] at (p1){};
\node[point] at (p2){};

\draw  let
\p1 = ($(p2) - (p1)$),
\n1 = {veclen(\x1,\y1)}
in
(p1) -- ($(p1)!0.2*\n1!(p2)$)node[pos=1,right] {\pgfmathparse{0.2*\n1}\pgfmathresult};
\end{tikzpicture}
\end{document} • 0.2*\n1 is equivalent to 0.2 in this context. Dec 4, 2014 at 14:39