Want to code a simple bouncing algorithm? If so, read this article and play with the GLSL Hacker demos.
Here is a set of simple demos showing some boxes bouncing at borders of the 3D window:
The core of the bouncing algorithm is this tiny Lua code:
px = px + (move_x*dt) py = py + (move_y*dt) if (px > winW/2) then px = winW/2 move_x = -move_x end if (px < -winW/2) then px = -winW/2 move_x = -move_x end if (py > winH/2) then py = winH/2 move_y = -move_y end if (py < -winH/2) then py = -winH/2 move_y = -move_y end
where:
- px and py are the 2D position of a box
- move_x and move_y are the speed
- winW and winH are the window size
You can find demos in the host_api/Bouncing_Boxes_2D/ folder of the code sample pack.
There are 2 demos:
- a demo that displays a single box and that uses the previous bouncing algorithm.
- a demo that displays 100 bouncing boxes with speed damping (see the video).
To run a demo, just load it in GLSL Hacker and hack the demo by editing the source code with your favorite text editor. That's all.