In this article I will consider such techniques as:
- The intersection of the dimensions of objects
- Belonging of a point to a polygon
And consider an example of the implementation of the mechanics of the game "Asteroids".
The intersection of the dimensions of objects
Almost any object / sprite can be entered into a rectangle, the length and width of which are the dimensions of the original object. Finding the intersection of dimensions is the first step to determining a collision. This operation does not require a lot of resources, so most often this function is used to find a pair of objects that need to determine a collision.
function MacroCollision(obj1,obj2){ var XColl=false; var YColl=false; if ((obj1.x + obj1.width >= obj2.x) && (obj1.x <= obj2.x + obj2.width)) XColl = true; if ((obj1.y + obj1.height >= obj2.y) && (obj1.y <= obj2.y + obj2.height)) YColl = true; if (XColl&YColl){return true;} return false; }
As can be seen from the source code, the definition of a collision is based on the definition of the intersection of the projections of rectangles on the X and Y axes. At the intersection, the function returns true, otherwise false.
')
Belonging of a point to a polygon
Let's imagine that we make such a game as "Asteroids". Each asteroid is an irregular polygon (polygon). Player bullet - a circle. Given the ratio of the scales of the asteroid and the bullet, you can neglect the size of the bullet, reducing to the center point of the circle. Thus, finding a collision is reduced to determining whether a point belongs to a polygon.
function pointInPoly(polyCords, pointX, pointY) { var i, j, c = 0; for (i = 0, j = polyCords.length - 1; i < polyCords.length; j = i++) { if (((polyCords[i][1] > pointY) != (polyCords[j][1] > pointY)) && (pointX < (polyCords[j][0] - polyCords[i][0]) * (pointY - polyCords[i][1]) / (polyCords[j][1] - polyCords[i][1]) + polyCords[i][0])) { c = !c; } } return c; }
As input parameters of the function - an array of vertices of the polygon and the coordinates of the point. The job description of this function is described in English
here .
Thus, we can easily determine the collision of a bullet with an asteroid. To reduce the number of calculations, we will initially use the finding of the intersection of dimensions, then the entry of a point in the polygon.
Example:
Bullet = function(x,y) {
What happened, you can download it
here , and a working example
here . WSAD + space control, click on the map - add asteroid.
UPDATE: A screenshot of what eventually came out as an example.
