\documentclass[11pt,a4paper]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
% CTC : center to center
% Distance is 2*sin(pi/3)
\def\ctc{1.7320508075688772cm}
% Draw an hexagon anywhere.
\def\hexagon#1{
%\draw #1 +(0:1cm) \foreach \a in {60,120,...,300} { -- +(\a:1cm) } -- cycle;
\fill[red] #1 circle (0.2cm);
}
% Draw a small hextile anywhere.
\def\hextile#1{
\foreach \l in {1,2} {
\foreach \a in {30,90,...,330} {
\hexagon{#1 ++(\a:\l*\ctc)};
}
\foreach \a in {0,60,...,300} {
\hexagon{#1 ++(\a:\l*3cm-3cm)};
}
}
}
\def\hextiles{
\foreach \a in {0,120,240} {
\hextile{(\a:6cm)};
}
}
%\hextiles;
\hextile{(0:6cm)};
\hextile{(120:6cm)};
\hextile{(240:6cm)};
\end{tikzpicture}
\end{document}
我很奇怪为什么,为什么打了三次\hextiles
电话\hextile
却没有得到相同的结果......
它似乎与路径的处理方式有关,但我不知道如何......
答案1
问题在于你\a
在循环中重复使用了宏\foreach
。当你这样做时
\def\hextiles{
\foreach \a in {0,120,240} {
\hextile{(\a:6cm)};
}
}
然后\hextile
使用参数进行调用字面上地 (\a:6cm)
。只要有 ,它就会被替换到命令中#1
。因此 的结果\hextile{(\a:6cm)}
就是将以下内容插入到流中:
\foreach \l in {1,2} {
\foreach \a in {30,90,...,330} {
\hexagon{(\a:6cm) ++(\a:\l*\ctc)}
}
\foreach \a in {0,60,...,300} {
\hexagon{(\a:6cm) ++(\a:\l*3cm-3cm)}
}
}
因此\a
最终使用的不是外循环的\a
,但\a
内循环的 。一种解决方案是简单地更改名称:
\documentclass[11pt,a4paper]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
% CTC : center to center
% Distance is 2*sin(pi/3)
\def\ctc{1.7320508075688772cm}
% Draw an hexagon anywhere.
\def\hexagon#1{
\draw #1 +(0:1cm) \foreach \a in {60,120,...,300} { -- +(\a:1cm) } -- cycle;
\fill[red] #1 circle (0.2cm);
}
% Draw a small hextile anywhere.
\def\hextile#1{
\foreach \l in {1,2} {
\foreach \a in {30,90,...,330} {
\hexagon{#1 ++(\a:\l*\ctc)}
}
\foreach \a in {0,60,...,300} {
\hexagon{#1 ++(\a:\l*3cm-3cm)}
}
}
}
\def\hextiles{
\foreach \b in {0,120,240} {
\hextile{(\b:6cm)}
}
}
\hextiles
%\hextile{(0:6cm)};
%\hextile{(120:6cm)};
%\hextile{(240:6cm)};
\end{tikzpicture}
\end{document}
更可靠的解决方案是确保\a
不按字面意思传递,而是使用其值。最好的方法取决于您将在什么情况下使用这些宏。