在网上查到以下代码,PGF and Tikz 中快速地画垂线
直接换成3D坐标,做出来的线貌似有问题,怎么解决
要想实现三维绘制垂线,需要自己做向量计算:
\documentclass[tikz,border=6pt]{standalone}
\usepackage{tikz-3dplot}
\usetikzlibrary{calc}
\begin{document}
\tdplotsetmaincoords{60}{110}
\begin{tikzpicture}[tdplot_main_coords]
% Axes
\draw[thick, ->] (0,0,0) -- (4,0,0) node[right] {$x$};
\draw[thick, ->] (0,0,0) -- (0,3,0) node[right] {$y$};
\draw[thick, ->] (0,0,0) -- (0,0,2) node[above] {$z$};
% Points
\coordinate (A) at (0,1,0);
\coordinate (B) at (3,2,0);
\coordinate (C) at (2.5,0,1);
% Labels
\path node[above] at (A) {$A$} node[above] at (B) {$B$} node[above] at (C) {$C$};
\fill[red] (A) circle (1pt) (B) circle (1pt) (C) circle (1pt);
% Compute projection D
\pgfmathsetmacro{\ABx}{3 - 0} % Bx - Ax
\pgfmathsetmacro{\ABy}{2 - 1} % By - Ay
\pgfmathsetmacro{\ABz}{0 - 0} % Bz - Az
\pgfmathsetmacro{\ACx}{2.5 - 0} % Cx - Ax
\pgfmathsetmacro{\ACy}{0 - 1} % Cy - Ay
\pgfmathsetmacro{\ACz}{1 - 0} % Cz - Az
% Dot products
\pgfmathsetmacro{\ABdotAB}{\ABx*\ABx + \ABy*\ABy + \ABz*\ABz}
\pgfmathsetmacro{\ACdotAB}{\ACx*\ABx + \ACy*\ABy + \ACz*\ABz}
% Parameter t for projection
\pgfmathsetmacro{\t}{\ACdotAB / \ABdotAB}
% Coordinates of D
\pgfmathsetmacro{\Dx}{0 + \t * \ABx}
\pgfmathsetmacro{\Dy}{1 + \t * \ABy}
\pgfmathsetmacro{\Dz}{0 + \t * \ABz}
% Draw projection
\coordinate (D) at (\Dx,\Dy,\Dz);
\fill[blue] (D) circle (1pt) node[right] at (D) {$D$};
\draw[cyan] (A) -- (B) (C) -- (D);
\end{tikzpicture}
\end{document}
核心思路是利用向量的投影和加减运算。
另外,下次提问请务必给可以编译测试的例子。