0

I was trying to simulate a bouncing ball (with no gravity) in a unit box and I managed to come up with a solution:

pred[x_] := 1 - UnitStep[x] + UnitStep[x - 1];
DynamicModule[{pos = {0.1, 0.5}, vel = {0.05, 0}, dt = 1}, 
 Graphics[{{White, EdgeForm[Directive[Black, Thick]], 
Rectangle[{-0.2, -0.2}, {1.2, 1.2}]}, 
Circle[Dynamic[
 Refresh[(vel = (pred[pos]*2 {-1, -1}*vel + vel); 
   pos = pos + vel*dt), UpdateInterval -> 1]], 0.02]}]]

But there is one problem: the graphic object does not update as frequently as required (once per second), instead it seems to update about 10+ times per second. However, if I changed the motion of the ball to a simpler sinusoidal motion, the graphic object seems to update at a desired frequency:

DynamicModule[{}, 
 Graphics[{{White, EdgeForm[Directive[Black, Thick]], 
   Rectangle[{-0.2, -0.2}, {1.2, 1.2}]}, 
   Circle[Dynamic[Refresh[pos={0.5Sin[Clock[Infinity]]+0.5,0.5},UpdateInterval->2]],0.02]}]]

So my questions are

1) Why UpdateInterval in the first case does not work properly, and

2) Is there any other way to dynamically update the positions of some points in a graphic object if the trajectory of these points cannot be pre-calculated (e.g. with collision involved) or represented as a function of time?

Any help is greatly appreciated.

zjx1805
  • 326
  • 2
  • 9
  • 2
    Ad 1) You need TrackedSymbols:>{}: Problem with UpdateInterval Ad 2) 38927 – Kuba Feb 24 '15 at 15:53
  • @Kuba That answers my questions. Thank you. – zjx1805 Feb 25 '15 at 05:59
  • @Kuba One more question, when running your code in question 38927, the kernel is always running so that I cannot do any other calculations. But with my code, after executing the kernel is not in the running status (so that I can perform other calculations in the same notebook session) and the graphic object keeps updating. So why a graphic object can keep updating itself with kernel unoccupied? – zjx1805 Feb 25 '15 at 06:55
  • The difference is that go[] command is just a loop sent with Shift+Enter. Your loop is whole in Dynamic. Dynamic communicates with Kernel with preemptive link and standard evaluation is done by main link. The latter is queued (my case), the former isn't (yours). At the end you can set my code so it uses preemptive link only. Take a look at Synchronous versus Asynchronous Dynamic Evaluations in AdvancedDynamicFunctionality tutorial but IntroductionToDynamic is a must too if you want to feel the subject – Kuba Feb 25 '15 at 07:30
  • I will look into it. Thank you for that. – zjx1805 Feb 25 '15 at 08:35

0 Answers0