0

Say we have a square and a point inside. How to make the point bounce off when it hits the walls. No gravity.

EDIT: New here, should've been more specific. The point has to fly in some random direction, not simply from side to side. What Kuba has commented

 x = 0.5;
 y = 0.5;

vx = 1;
vy = Pi/2;

step = 0.01;
radius = 0.05;

Animate[
  x = x + vx*step;
  y = y + vy*step;
  If[Abs[x - 1] <= radius || Abs[x] <= radius , vx = -vx];
  If[Abs[y - 1] <= radius || Abs[y] <= radius, vy = -vy];
  Graphics[{
    Cyan, Rectangle[{0, 0}, {1, 1}],
    Gray, Disk[{x, y}, radius],
    Point[{0.0, 0.0}], Point[{1.0, 1.0}]
  }],
  {t, 0, Infinity}
]

seems cool, but it's a disk and if I were to draw a line inside the rectangle, it would simply fly through it. I'm currently checking out the other solutions on that page, but having a hard time since they're a bit too complex for my purpose.

Basically, what I need is a point bouncing off any line(s) I draw. I just used a square as an example. Hopefully this is more understandable.

12345
  • 3
  • 2
  • 4
    Could you give us the code you're currently working with? There are myriad ways to do this, so if you can show us how you're approaching it we can make this work nicer for you. – b3m2a1 Dec 03 '19 at 21:41
  • Check this out: https://mathematica.stackexchange.com/q/38927/5478 – Kuba Dec 04 '19 at 08:04

1 Answers1

5

No gravity. Ball keeps bouncing off the wall. Using Manipulate.

enter image description here

code

Manipulate[
 (*version 12/3/2019 7:40 PM*)
 gTick;
 Pause[speed];
 If[runningState == "RUNNING",
  gTick = Not[gTick];
  If[direction == "RIGHT",
   If[x >= ( 1 - ballRadius), direction = "LEFT"]
   ,
   If[x <= ballRadius, direction = "RIGHT"]
   ];
  If[direction == "LEFT", x = x - 0.01, x = x + 0.01
   ]
  ];

 g = Graphics[{
    {EdgeForm[Black], FaceForm[], Rectangle[{0, 0}, {1, 1}]},
    {Red, Disk[{x, 0.5}, ballRadius]}
    },
   PlotRange -> {{0, 1}, {0, 1}},
   ImageSize -> 400, Axes -> True,
   GridLines -> {Range[0, 1, 0.1], Range[0, 1, 0.1]},
   GridLinesStyle -> Directive[LightGray]
   ],

 Grid[{
   {Button[
     Style["run", 12], {runningState = "RUNNING"; gTick = Not[gTick]},
      ImageSize -> {55, 35}],
    Button[
     Style["stop", 12], {runningState = "STOP"; gTick = Not[gTick]}, 
     ImageSize -> {55, 35}]}
   }
  ],
 {{x, 0.5}, None},
 {{runningState, "STOP"}, None},
 {{direction, "RIGHT"}, None},
 {{gTick, True}, None},
 {{ballRadius, 0.01, "Ball radius?"}, 0.01, 0.3, .01, 
  Appearance -> "Labeled"},
 {{speed, 0.01, "speed?"}, 0, 0.3, .01, Appearance -> "Labeled"},
 TrackedSymbols :> {gTick, ballRadius},
 SynchronousUpdating -> True
 ]
Nasser
  • 143,286
  • 11
  • 154
  • 359