Home >Web Front-end >JS Tutorial >JavaScript enhancement tutorial - cocosjs collision detection
This article is the official HTML5 training tutorial of H5EDU organization. It mainly introduces: JavaScript enhancement tutorial - cocosjs collision detection
Briefly describe the collision detection principle of the game: First, specify a collision detection area for each game object, and then in the Update method Detect whether the areas of two objects overlap in real time. If so, then a collision occurs.
Have a brief look at the code. This code is extracted from the official code.
tools.CollisionHelper={ IsCollided:function(ccA,ccB){ var ax = ccA.x, ay = ccA.y, bx = ccB.x, by = ccB.y; /*if (Math.abs(ax - bx) > 5|| Math.abs(ay - by) >5) { return false; }*/ var aRect = this.MakeCollideRect(ccA); var bRect = this.MakeCollideRect(ccB); return cc.rectIntersectsRect(aRect, bRect); }, MakeCollideRect: function (ccA) { return cc.rect(ccA.x - 3, ccA.y - 3, 20, 20); } };
Briefly explain the code: During collision detection, the collision area of each game object is compared (in the above code, we set the height and width of the area Both are 20. The coordinates of this area are the coordinates of the current game object minus 3. This 3 must be dynamically adjusted according to different objects in the game). After getting the locations of these two areas, just send them to the cc.rectInterestsRect function. In fact, area range detection is also done inside the cc.rectInterestsRect function.
If you want to hide the game object after a collision, just use: gameObject.setVisibility(false).
By using the collision detection results with cc.fadeIn and cc.fadeOut, you can easily create a collision animation