Home > Web Front-end > JS Tutorial > body text

JavaScript enhancement tutorial - cocosjs collision detection

巴扎黑
Release: 2016-12-05 11:19:45
Original
1172 people have browsed it

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); 
     } 
 };
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!