6
$\begingroup$

Description

It probably has a simple fix but I can't seem to find a way.

I am looking to generate a set of random points within a dynamic region. Each time a new type of region is selected, the random points must be generated accordingly to fit within region boundaries. Please see an example below.

Example:

Code

 DynamicModule[
 {
  shape = {},
  targets
  },
 Panel @ Column @ {
    Item[RadioButtonBar[Dynamic @ shape, {Disk[] -> "Disk", Rectangle[] -> "Rectangle"}], Alignment -> Center],

    Dynamic[targets = If[Length @ shape != 0, RandomPoint[shape, 10]]];

    Dynamic @ Graphics[{
       {FaceForm @ White, EdgeForm @ Black, shape},
       Point @ # & /@ targets
       }]
    }
 ]

Output

Error Message

Error

targets$$ is not a Graphics primitive or directive

However if in the following line of code (see below) ; is replaced with ,, the code works but it also displays all the {x,y} coordinate pairs. I would like to avoid that.

Code

Dynamic[targets = If[Length @ shape != 0, RandomPoint[shape, 10]]];

Output

working example

I am after similar output as above but without displaying {x,y} coordinates.

$\endgroup$
12
$\begingroup$

I would suggest using the second argument of Dynamic:

DynamicModule[{shape = Disk[], targets = RandomPoint[Disk[], 10]},
 Panel@Column@{
    Item[
     RadioButtonBar[Dynamic[
       shape,
       (targets = RandomPoint[#, 10]; shape = #) &
       ], {Disk[] -> "Disk", Rectangle[] -> "Rectangle"}],
     Alignment -> Center
     ],
    Dynamic@Graphics[{
       {FaceForm@White, EdgeForm@Black, shape},
       Point@# & /@ targets
       }]
    }]

enter image description here

The second argument is used to tell Dynamic what to do when the selection in the button bar is changed. By default Dynamic just updates its first argument to the corresponding value, but you can also tell it to "first update targets and then update shape".

$\endgroup$
  • $\begingroup$ Thank you! Very helpful, I knew there was an easy work around this issue. I will accept the answer later in the day (travelling) $\endgroup$ – e.doroskevic Jun 1 '16 at 16:09

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.