Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am drawing a surface composed of rigid "molecules" composed of three spheres each. I want to add some randomness to the surface. I have created this code:

\begin{tikzpicture}
  \def\nuPi{3.1459265}
  \foreach \i in {11,10,...,0}{
    \foreach \j in {5,4,...,0}{
      \def\dx{rand*0.1}
      \def\dy{rand*0.1}
      \shade[ball color=red]  (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)}) circle(0.45);
      \shade[ball color=gray] (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)-0.9}) circle(0.45);
      \shade[ball color=gray] (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)-1.8}) circle(0.45);
    }
  }

\end{tikzpicture}

judging by the resulting surface, the \dx and \dy are generated each time they are accessed and not once in each loop. Is there a way to store them?

share|improve this question
add comment

1 Answer

up vote 11 down vote accepted

You can store the results using \pgfmathsetmacro{<macro>}{<expression>}. Note that the the argument to functions like sin(<arg>) should be given in degrees by default. If not, you should use the "r operator". For more on parsing mathematical expressions, read section 63 Syntax for mathematical expressions (p 527 onward) in the tikz/pgf documentation.

I've modified you code snippet into an MWE and used (\xcoor,\ycoor) to represent the coordinate pair, since they were basically the same for the three shaded balls.

enter image description here

\documentclass{article}
\usepackage{tikz}% http://ctan.org/pkg/pgf
\begin{document}
\begin{tikzpicture}
  \foreach \i in {0,1,...,11}{
    \foreach \j in {5,4,...,0}{
      \pgfmathsetmacro{\xcoor}{\i+rand*0.1}% x-coordinate
      \pgfmathsetmacro{\ycoor}{0.5*\j+rand*0.1+.4*sin(\i*360/12)}% y-coordinate
      \shade[ball color=red]  (\xcoor,\ycoor) circle(0.45);
      \shade[ball color=gray] (\xcoor,\ycoor-0.9) circle(0.45);
      \shade[ball color=gray] (\xcoor,\ycoor-1.8) circle(0.45);
    }
  }
\end{tikzpicture}
\end{document}
share|improve this answer
    
Thanks. While at it, do you know why I have to multiply the sin argument by 10 to get the wave? –  Yotam Jan 9 '12 at 21:07
    
@Yotam: I've updated my answer. The argument of sin has to be an angle in degrees. If you want to specify it in radians, you need to use the r operator. –  Werner Jan 9 '12 at 21:30
    
Great. Thanks. I can't re-select your answer. –  Yotam Jan 10 '12 at 13:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.