box2d physics engine simulates bomb explosion effect

Source: Internet
Author: User

Let's simulate the bomb effect today. So the question comes: "Why imitate such a violent effect?" Is it not for a few days, yorhom character change? ”

In fact, the students who have played Angry birds should be familiar with this effect, because according to unofficial reports, the second most powerful bird-black bird stunt is self-destruct. The second question arises: "What kind of bird is the first?" "According to Yorhom I personally test, the red bird should be the most powerful, but seemingly no stunts?" Angry Birds this superficial game, y some I am best at, after a time will be dedicated to write this game raiders. The two birds ' pictures are as follows:


Perfunctory asked questions two students, the problem three came: "How to achieve this effect?" "The problem is not perfunctory, so the next article, I will introduce you how to use box2d to achieve this effect."

Before you learn this chapter, you need to know about box2d, a very useful and well-known physics engine. With my personal learning experience, I recommend to you the Uncle Bin Laden's blog, the blog box2d column address as follows:

http://www.ladeng6666.com/blog/category/box2d/


One, the bomb effect principle

In achieving this effect, I think of two scenarios.

Scenario One: when the bomb rigid body explosion, from the bomb rigid body as a starting point, scattered around the small rigid body, these small-just experience is sprayed to the nearby rigid body, to the nearby rigid body force, and then force is the object motion state Change Reason (excerpt from high school physics compulsory one), then the explosion effect can be completed. This method is relatively simple, but I feel a little dirty way. I have a headset labeled R must be with the right side, marked with L must be with the left side of the person, how can this be satisfied? Of course, interested friends can try this method for themselves ~

Scenario Two: first of all to find out the bomb rigid body around the other rigid bodies, and then exert a force on them, we can only control the direction of the force to achieve the explosion effect. Yes, good. It seems that this method is more beautiful ~

The obvious difference between the two scenarios is that programme two is a little less than a word. What does that mean? I think, we should have done at least 6 years of math problem, according to my experience for about 9.5 years, the less the number of questions the math problem is more difficult, because the amount of information provided less. So, while the two effects are relatively better, the implementation may be much more complex.

Scenario Two is more difficult to achieve, is that we do not know how to find the surrounding rigid bodies. To this end, I have dabbled in all the features I've learned about box2d, and found that I've never used a feature I've just heard of-ray casting might come in handy. But Xin good online related to a lot of information, so I learned a bit about b2raycastinput,b2raycastoutput these two classes.

The above two classes are important, so you must first understand these two classes, the specific tutorial is: http://ohcoder.com/blog/2012/12/10/ray-casting/, the tutorial is box2d C + +, but whether it is C + + or Web version, The usage is the same.

B2raycastinput,b2raycastoutput What is the use of these two classes? As you can see from the tutorials provided above, instances of these two classes are typically passed into the B2fixture raycast function as parameters, which is used to check if a ray is intersecting a rigid body. So we only use the bomb rigid body position as the starting point, and then spray the radiation around. It then loops around the world's rigid bodies, judging whether the resulting rigid bodies intersect with the rays, and if they intersect, exert a force on the current rigid body. In this way, the principle of bomb effect is basically clarified.


Second, build a physical world

First, create the most basic world. So, we add the following code to the index.html:

<! DOCTYPE html>
The HTML code is not the focus, the focus is main.js:

Window.addeventlistener ("Load", Main, false); var b2vec2 = Box2D.Common.Math.b2Vec2, B2aabb = Box2D.Collision.b2AABB, B2bodydef = Box2D.Dynamics.b2BodyDef, B2body = Box2D.Dynamics.b2Body, b2fixturedef = Box2D.Dynamics.b2FixtureDef, B2fixture = Box2D.Dynamics.b2Fixture, B2world = Box2D.Dynamics.b2World, B2massdata = Box2D.Collision.Shapes.b2MassData , B2polygonshape = Box2D.Collision.Shapes.b2PolygonShape, B2circleshape = Box2D.Collision.Shapes.b2CircleShape, B2debugdraw = Box2D.Dynamics.b2DebugDraw, B2mousejointdef = Box2D.Dynamics.Joints.b2MouseJointDef, B2raycastinput = Box2D.Collision.b2RayCastInput, b2raycastoutput = Box2d.collision.b2raycastoutput;var World, fixdef, Bodydef;var bomb = Null;var Timer = 0;function Main () {world = new B2world (new b2vec2 (0, 9.8), true); fixdef = new B2fixturedef (); fixdef.de nsity = 1.0;fixdef.friction = 0.5;fixdef.restitution = 0.2;bodydef = new B2bodydef (); Createground (); CreateBlocks (); Createbomb (); Createdebugdraw (); setinterval (update, 1000/60);} Function Createground () {fixdef.shape = new B2polygonshape (); FixDef.shape.SetAsBox (1); bodydef.type = b2body.b2_ Staticbody;bodydef.position.set (Ten); Createbody (Bodydef). Createfixture (fixdef);} function Createblocks () {var list = [{width:120, height:30, x:140, y:330},{width:20, height:100, x:50, y:  200},{width:20, height:100, x:230, y:200},{width:120, height:20, x:140, y:80},{width:120, height:30, X : Y:330},{width:20, height:100, x:350, y:200},{width:20, height:100, x:530, y:200},{width:120, H Eight:20, x:440, y:80}];for (var i = 0; i < list.length; i++) {var data = List[i];fixdef.shape = new B2polygonsha PE (); FixDef.shape.SetAsBox (Data.width/30, data.height/30); bodydef.type = B2body.b2_dynamicbody; BodyDef.position.Set (DATA.X/30, DATA.Y/30); Createbody (Bodydef). Createfixture (Fixdef);}} function Createbomb () {fixdef.shape = new B2circleshape (0.5); bodydef.type = B2body.b2_dynamicbody;bodydef.position. Set (9.7, 1); bomb = world. Createbody (bodydef); bomb.userdata = "Iambomb"; bomb. Createfixture (fixdef);} function Createdebugdraw () {var debugdraw = new B2debugdraw ();d ebugdraw.setsprite (document.getElementById ("MyCanvas" ). GetContext ("2d"));d Ebugdraw.setdrawscale (30.0);d Ebugdraw.setfillalpha (0.5);d ebugdraw.setlinethickness (1.0); Debugdraw.setflags (b2debugdraw.e_shapebit | b2debugdraw.e_jointbit | b2debugdraw.e_controllerbit | b2DebugDraw.e_ Pairbit); Setdebugdraw (Debugdraw);} function Update () {world. Step (1/60, ten); Drawdebugdata (); Clearforces (); if (timer++ = =) {detonated ();}}
It is important to note that the timer variable, which is used to clock the explosion. In the update function we call the dentonated function, I temporarily do not publish this function code, this function is used to detonate bombs.
To run the code, we get the physical world:

The small ball in the picture is actually a bomb.


Three, detonate the bomb.

The above mentioned dentonated function, here, we will learn the code inside, this is the core part of this development.

function detonated () {var position = bomb. Getworldcenter (); var range = 3;for (var i = 0; I <=; i++) {var angle = 360/100 * I;var input = new B2raycastinput (); input.p1 = Position;input.p2.set (position.x + range * Math.Cos (angle), POSITION.Y + range * Math.sin (angle)); Input.max Fraction = 1;var output = new B2raycastoutput (); for (var currentbody = world. Getbodylist (); Currentbody; Currentbody = Currentbody.getnext ()) {if (Currentbody.userdata = = Bomb.userdata) {continue;} The var fix = Currentbody.getfixturelist (); if (!fix) {continue;} var ishit = fix. RayCast (output, input), if (Ishit) {var p1 = input.p1.Copy (), var p2 = input.p2.Copy ();p 2. Subtract (p1);p 2. Multiply (output.fraction);p 1. ADD (p2); var hitPoint = P1. Copy (); hitpoint.subtract (position); Currentbody.applyforce (New B2vec2 (Hitpoint.x * (1-output.fraction) * 300, HITPOINT.Y * (1-output.fraction) *, hitPoint);}} World. Destroybody (bomb);}
In this function, I first use the getworldcenter to get the position of the bomb rigid body, and then set a range of explosion ranges variable. The ray is then created around the loop. Here I set a total of 100 rays to be sprayed, so the angle between each ray is 3.6 degrees. Knowing the angle, we can calculate the end point of each ray vector and pass the end point and the origin to the b2raycastinput.

After the preparation of a series of rays, we begin to cycle the rigid bodies in the world. The resulting rigid body gets a B2fixture object and calls the raycast of the model to determine if the ray just created intersects the rigid body.

if (ishit) {var p1 = input.p1.Copy (), var p2 = input.p2.Copy ();p 2. Subtract (p1);p 2. Multiply (output.fraction);p 1. ADD (p2); var hitPoint = P1. Copy (); hitpoint.subtract (position); Currentbody.applyforce (New B2vec2 (Hitpoint.x * (1-output.fraction) * 300, HITPOINT.Y * (1-output.fraction) *, hitPoint);}
The above lines of code are responsible for calculating the vector of the position where the ray intersects the rigid body and applying a force at that position. So how do you calculate the vectors that correspond to the positions where the rays intersect the rigid bodies? We might as well take a look at the picture:

Now, let us mobilize the high school mathematics compulsory four-level knowledge of the volume. So the math problem came: Known vector Op1,Op2 coordinates, and p1,p2,p3 three points collinear,p1p3 = n p1p2, seeking Op3.

To solve this problem, you can use a fixed score point and other knowledge, with vector addition and subtraction, the number multiplication operation can also solve the problem. Here are my answers:


Solution set P1 (x1, y1), p2 (x2, y2)

Op3 = Op1 + p1p3 = np1p2 + Op1 = N (x2-x1, y2-y1) + (x1, y1) = (nx2-nx1 + x1, ny2-ny1 + y1)


This is a mathematical notation, in the program code is:

var p1 = input.p1.Copy (), var p2 = input.p2.Copy ();p 2. Subtract (p1);p 2. Multiply (output.fraction);p 1. ADD (p2); var hitPoint = P1. Copy ();
The output.fraction here is equal to the n given by the title. Copy,substact,add,multiply are used to copy the current vector, vector subtraction, vector addition, vector number multiplication operations.

After calculating the collision position, we apply a force to the rigid body with applyforce, and then the rigid body is similar to the air shock generated by an explosion and flies out ~

The bomb exploded, and the bomb itself must be destroybody, so after exerting force on the surrounding rigid body, destroy the bomb rigid body


Run the code and get:

Online test address:http://wyh.wjjsoft.com/demo/box2d_bomb/

Source code:http://wyh.wjjsoft.com/downloads/box2d_bomb.zip


This is the end of this chapter, you are welcome to leave a message ~

----------------------------------------------------------------

Welcome you to reprint my article.

Reprint Please specify: Turn from Yorhom's Game box

Http://blog.csdn.net/yorhomwang

Welcome to follow my blog

box2d physics engine simulates bomb explosion effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.