Constrain Locator to specified region
How can I constrain the
Locator
to stay within the region defined byRegionPlot
?You can check if
Locator's
coordinates fulfill the condition defining your region. It can be done with the second argument ofDynamic
if you introduceLocator
explicitly. Take a look at line withLocator[Dynamic[p, With[{...
A strange behavior occurs whenever the left mouse button is pressed: the right end of the region is truncated. Why?
The body of a
Manipulate
is effectively wrapped withDynamic
. Each time you move something, it will be evaluated. During dynamic evaluation$PerformanceGoal
is set to"Speed"
unless you change it. It results in less sampling points and cut corners.You can change it to
"Quality"
but here there is no point in evaluatingregion
each time anyway. It is independent fromT
andp
so let's do it outside, once for good.
Edit:
Your answer is just what I wanted though I need to create a CDF demo. Unfortunately I obtained an error message upon creating a CDF from your answer.
That's because
region
definition is forgotten as soon as the Kernel is quit, in contrast toManipulate
s andDynamicModule
s variables generated "on fly" likesol
andpsol
here.You can use
SaveDefinitions->True
or inject theregion
withWith
.I also tried to change the appearance of the locator to a disk but was challenged there as well.
For custom
Locators
it is better to setAppearance->None
and display whatever you want in its coordinates.
With[{
region = RegionPlot[y^2 < x^2*(1 + x/6), {x, -6, 0}, {y, -2.5, 2.5}]
},
Manipulate[
sol = NDSolve[
{x'[t] == y[t], y'[t] == x[t] + x[t]^2/4,
x[0] == p[[1]], y[0] == p[[2]]},
{x, y}, {t, 0, T}
];
psol = ParametricPlot[Evaluate[{x[t], y[t]} /. sol], {t, 0, T},
PlotRange -> {{-6, 0}, {-3, 3}}, PlotStyle -> Red
];
Show[{
region, psol,
Graphics[{
Dynamic @ Disk[p, .1],
Locator[Dynamic[p,
With[{x = #[[1]], y = #[[2]]}, If[y^2 < x^2*(1 + x/6), p = #]] &],
Appearance -> None
]
}]
},
AspectRatio -> Automatic
],
{{p, {-2, 0}}, None}, {{T, 5}, 0, 12, 0.1}
]]