我正在尝试修改代码以便可以移动立方体。目标是绘制 3 个连接在一起的立方体,每个立方体都有不同的颜色。不知何故,(0,0,0) 没有移动。((node)-- ++ (node) 是什么意思?)
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro{\cubex}{2}
\pgfmathsetmacro{\cubey}{1}
\pgfmathsetmacro{\cubez}{1}
\pgfmathsetmacro{\shift}{1}
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,-\cubey,0) -- ++(\cubex,0,0) -- cycle;
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(0,0,-\cubez) -- ++(0,-\cubey,0) -- ++(0,0,\cubez) -- cycle;
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,0,-\cubez) -- ++(\cubex,0,0) -- cycle;
\end{tikzpicture}
\end{document}
我不想使用 pdfplot 包,因为它与其他代码冲突。
答案1
我建议您为立方体定义一个宏并用scope
它来移动它:
笔记:
++
语法中的表示-- ++
下一个坐标是相对于当前坐标的偏移量。因此,以下两个\draw
命令是等效的:\draw (2,3) -- (6,8); \draw (2,3) -- ++(4,5);
请注意,
\pgfmathsetmacro
将结果转换为实数,而\pgfmathtruncatemacro
则不转换。在这种情况下,这并不重要,但在其他情况下可能很重要。
代码:
\documentclass{article}
\usepackage{tikz}
\newcommand*{\MyCube}[4][]{%
\draw[join=round,red,fill=yellow,#1] (0,0,0) -- ++(-#2,0,0) -- ++(0,-#3,0) -- ++(#2,0,0) -- cycle;
\draw[join=round,red,fill=yellow,#1] (0,0,0) -- ++(0,0,-#4) -- ++(0,-#3,0) -- ++(0,0,#4) -- cycle;
\draw[join=round,red,fill=yellow,#1] (0,0,0) -- ++(-#2,0,0) -- ++(0,0,-#4) -- ++(#2,0,0) -- cycle;
}%
\begin{document}
\begin{tikzpicture}
\pgfmathtruncatemacro{\cubex}{2}
\pgfmathtruncatemacro{\cubey}{1}
\pgfmathtruncatemacro{\cubez}{1}
\begin{scope}
\MyCube[ultra thick]{\cubex}{\cubey}{\cubez}
\end{scope}
\begin{scope}[shift={(2,0)}]
\MyCube[ultra thick,blue,fill=brown!25]{\cubex}{\cubey}{\cubez}
\end{scope}
\begin{scope}[shift={(4,0)}]
\MyCube[ultra thick,orange,fill=green]{\cubex}{\cubey}{\cubez}
\end{scope}
\end{tikzpicture}%
\end{document}
答案2
您忘记了 之前的反斜杠shift
。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro{\cubex}{2}
\pgfmathsetmacro{\cubey}{1}
\pgfmathsetmacro{\cubez}{1}
\pgfmathsetmacro{\shift}{1}
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,-\cubey,0) -- ++(\cubex,0,0) -- cycle;
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(0,0,-\cubez) -- ++(0,-\cubey,0) -- ++(0,0,\cubez) -- cycle;
\draw[red,fill=yellow] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,0,-\cubez) -- ++(\cubex,0,0) -- cycle;
\pgfmathsetmacro{\shift}{3}
\draw[blue,fill=red] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,-\cubey,0) -- ++(\cubex,0,0) -- cycle;
\draw[blue,fill=red] (0+\shift,0,0) -- ++(0,0,-\cubez) -- ++(0,-\cubey,0) -- ++(0,0,\cubez) -- cycle;
\draw[blue,fill=red] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,0,-\cubez) -- ++(\cubex,0,0) -- cycle;
\pgfmathsetmacro{\shift}{5}
\draw[yellow,fill=blue] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,-\cubey,0) -- ++(\cubex,0,0) -- cycle;
\draw[yellow,fill=blue] (0+\shift,0,0) -- ++(0,0,-\cubez) -- ++(0,-\cubey,0) -- ++(0,0,\cubez) -- cycle;
\draw[yellow,fill=blue] (0+\shift,0,0) -- ++(-\cubex,0,0) -- ++(0,0,-\cubez) -- ++(\cubex,0,0) -- cycle;
\end{tikzpicture}
\end{document}