JavaScript/Exercises/Collisions

Speed
When objects move around, they do this at a certain speed. Therefore you should add two properties to the object's  representing its speed in x-direction and in y-direction. Positive values represent the direction to the right resp. bottom, and negative to the left resp. top. Furthermore, the class needs functions to modify the speed.

Collision - 1
Objects can collide with other objects or with the border of the canvas. Algorithms to detect such collisions depend on the object's type: concerning the x-direction for rectangles, the left side is given by the starting point, and for circles, the left side must be computed from the central point and the radius. A collision with the canvas' border is a collision 'from inner to outer', a collision between objects is always 'between outer and outer'.

Nevertheless, it's possible to develop generic algorithms that solve many of the 'collision' problems. Every single 2-dimensional object and every group of such objects can be surrounded by their minimum bounding box (MBB), which is a rectangle by definition. Hence the collision of objects can be solved by an algorithm that detects the collision of their MBBs, at least in the first approximation. It is not absolutely exact in all cases, but for our examples, it should be sufficient.

Constant speed
We create a ball (circle) and let him move within the canvas.
 * As usual, the function  contains the 'logic' of the game. It is straightforward: move the ball according to it's 'speed'. The 'speed' is the number of pixels by which it should advance.
 * A function  checks whether the border of the canvas is touched by the current step. If that is the case, the speed is reversed to the opposite direction.
 * checks whether the border of a rectangle is touched by a rectangle that moves within its inner space. This is different from the case where two rectangles collide like two cars.
 * The 'outer' rectangle is the canvas itself. We use its properties as the four first arguments of the function call.
 * The ball inside the canvas is not a rectangle; it's a circle. We 'compute' the MBB of the circle and use the properties of the MBB as the four last arguments of the function call. (For this algorithm, the MBB delivers not only an approximation of the problem, it's an exact solution.)

Changing speed
The example is identical to the above one with the additional feature of changing the speed of the ball. It adds two HTML elements  as a slider. The sliders indicate the intended speed in x- and y- directions.

Collision - 2
The example is identical to the above one with the additional feature of detecting an obstacle (rectangle). If the ball collides with the obstacle, the game stops.

The collision is detected by the function. It compares two rectangles. We use the MBB of the circle as the second parameter, which leads to a slight inaccuracy.