3

I need to insert in the rectangle all my 10 molecules in random way (angle and x,y position). I don't know what is wrong with my code.

enter image description here

\startMPinclusions

vardef spring (expr a, b, w, h, n) =
pair vec ; path pat ; numeric len ; numeric ang ;
vec := (b-a) ;
pat := for i=1 upto n-1: (if odd(i):-fi w/2,i)--endfor (0,n) ;
pat := (0,0)--(0,h)-- pat shifted (0,h)--(0,n+h)--(0,n+2h) ;
len := (xpart vec ++ ypart vec)/(n+2h) ;
ang := -90+angle(vec) ;
( pat yscaled len rotatedaround(origin,ang) shifted a )
enddef ; 

\stopMPinclusions

\enabletrackers
  [metapost.showlog]
\starttext

\starttext




\startMPcode
tracingall;
picture molecule;
path p ; p :=(.1cm,0)--spring((.2cm,0),(2.5cm,0),.5cm,0,10)--(2.6cm,0) ;

draw p;
draw fullcircle scaled 2cm shifted(-0.9cm,0);
draw fullcircle scaled 2cm shifted(3.6cm,0);
molecule := currentpicture scaled .1;currentpicture:=nullpicture;

numeric angulo; numeric xx; numeric yy; pair par;

for i=1 step 1 until 10:
angulo:=uniformdeviate 180;
xx:=uniformdeviate 80; 
yy:=uniformdeviate 50;
par:=(xx,yy);
draw molecule shifted par rotated angulo ;
endfor;

%clip currentpicture to (0,0)--(0,2cm)--(3cm,2cm)--(3cm,0)--cycle;
draw (0,0)--(0,2cm)--(3cm,2cm)--(3cm,0)--cycle withcolor 0.625red;
\stopMPcode

\stoptext
4

Replacing this

draw molecule shifted par rotated angulo ; 

by this one

draw molecule rotated angulo shifted par;

gives a better (yet still not perfect) result:

enter image description here

(The rotation made by rotated is always centered at the origin, hence the former behavior. You can also use the line

draw molecule shifted par rotatedaround(par, angulo);

instead).

EDIT

I've just replaced the line defining your red bounding box,

 draw (((0,0)--(0,2cm)--(3cm,2cm)--(3cm,0)--cycle) withcolor 0.625red;

by

 draw (((0, 0)--(0, 50)--(80, 50)--(80, 0)--cycle) enlarged .46cm) withcolor 0.625red;

which is more precisely fitted to the parameters:

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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