HTML5 Physics game development-off-road mountain bikes (iii) Crush bikes

Source: Internet
Author: User
Tags addchild

Since the last chapter released to now has been a lapse of April, really sorry everybody, let everybody wait for a long time ~ say not I do not pay attention to my blog, but the matter a lot up to write a blog less. Until today is free, looked back to look at his previous writing article, fierce to find already four months have not written article, then had to call: "Bitter also ~", I fear this series of articles will drag longer, so immediately pen, also good for this series of articles leave a tail.

First of all, let's brush up on the contents of the previous two articles:

HTML5 Physics game development-off-road mountain Biking (ii) create a controllable bike

http://blog.csdn.net/yorhomwang/article/details/21300253

HTML5 Physics game development-off-road mountain biking (i) creating a variety of terrains

http://blog.csdn.net/yorhomwang/article/details/19710537


What we're going to do today is--when the key part of our bike hits the wall, it immediately shatters it, and the popular point is "bike breaks." Ok, gossip Why more say, we began

Let's put two cards on it:





※ Again, this development uses the Lufylegend.js Open source HTML5 game engine and Box2dweb physics engine, please go to the official website to download the use. The official website address has been mentioned in the first chapter.


first, the principle of crushing

Anyone with a hammer knows (if you haven't used it, and you don't know how to use it, suggest you ask Thor Saul), how do you smash a bike? If you don't, I'll teach you three tricks:

Law one: Hit hard; This method is suitable for you want to change the hammer

Law two: to Ascar to find thunder God eldest brother Go, this rate is the fastest, estimated not to smoke a cigarette, your bike is only atoms

Law three: Go somewhere and replace the hammer with a screwdriver or something, and then remove the part of your bike.

Obviously, these three methods have their own merits, but since our bicycle is a piece of land together, then it is a piece of ground to dismantle, so, I chose 3 (actually because Box2dweb no hammer this thing, also recognize Thor). We mentioned in the previous chapter how to put the parts together, the principle is to use the joints in the box2dweb, these joints connect the parts together, then if these joints are destroyed, then these parts will be scattered. But how do we destroy the joints? There is a destroyjoint function in Box2dweb's B2world, and the parameter is the B2joint object you want to destroy. Let's see how the joints are destroyed in the lufylegend.

First, the function that passes through the LBOX2D key joint in Lufylegend will return the created B2joint object, which means:

var j = LStage.box2d.setRevoluteJoint (A.box2dbody, b.box2dbody); LStage.box2d.world.DestroyJoint (j);
We can save the rotary joint created by the call Setrevolutejoint in the variable J, then call the LStage.box2d.world.DestroyJoint function directly when destroying it, and the parameter is J.

What if we have multiple joints? Put the array in the BAI, presumably smart you before I said that before you have thought of this.
The principle is done, so let's start looking at the code.


Two, update bike class and main class

In the previous chapter we focused on how to achieve the bicycle class, this time because to crush it, so we have to first operate on it, put a few bombs to talk about. Before the bomb is ready to be prepared, so as not to blow up over, so you have to make a box to blow up the place to pack up. happened to main class passing (about main please look at the first chapter), I put it in one hand to come over, sing a sound, the way: "You temporarily for me to pack two things, how?" "The main class thought:" This man can take charge of all the procedures, in case this is a fire, a delete to me and so delete a clean is not a good thing. , and he resigned himself to this task. But said crossing want to know what two things? It turns out to be an array called jointlist and a bool variable named Gameovercontroller; The two of them are one tube-mounted all the resulting joints, and a tube game is over. So the constructor of main is reconstructed as follows:

function Main () {var s = this;base (s,lsprite,[]);/** set scene size */s.scenewidth = 8500;s.sceneheight = lstage.height+1000;/** Joint List */s.jointlist = new Array ();/** game End Controller */s.gameovercontroller = FALSE;}

But said above that paragraph obviously some water margin of style, sorry, recently "outlaws of the marsh" to see more, hope you include.

We know that bombs are going to be a bit of FireWire, or a higher level of switch Ah, anyway, is a detonator, this job is to the main bar. To modify the Init method of main:

Main.prototype.init = function () {var s = this;/** joins the Border */s.addborder ();/** joins the Pavement */s.addroad ();/** join Bike */s.addbicycle () ;/** joins the rigid Body collision event */lstage.box2d.setevent (Levent.post_solve,s.postsolve);/** joins the cyclic event */s.addeventlistener (LEvent.ENTER_ Frame,s.loop);};

The main one is to add a call to the LStage.box2d.setEvent function. This function is a method of the Lbox2d class (Lstage.box2d is an instantiated object of lbox2d), which is used in this way:

SetEvent (Type, func)

Parameter description:

Type box2d collision event types in the world

function dispatched when Func triggers an event

The type of collision event can be:

Levent.begin_contact: This function will be triggered when the collision is just started.
Levent.end_contact: This function is triggered at the end of the collision.
Levent.post_solve: This function is processed after a collision
Levent.pre_solve: When a collision is imminent


Here we choose the post_solve, that is, after the collision will deal with this function, in fact, choose other event types, the effect should be the same. The function dispatched when the event is triggered is postsolve, and this function is also given to main bar ~ [Main class: A good pack of two (T_T)]

Main.prototype.postSolve = function (Contact) {if (World.gameovercontroller) return;var L = world.jointlist;if (l.length = = 0) return;//Gets the Lsprite object of the collision var CA = contact. Getfixturea (). GetBody (). Getuserdata (); var CB = contact. Getfixtureb (). GetBody (). Getuserdata ();//Determine whether to destroy the bicycle if (//--------------------------------------------//Condition One: When the bicycle and the wall collide//------------------- -------------------------((ca.name== "Wall" && cb.name== "bicycle") | | (ca.name== "Bicycle" && cb.name== "Wall")) | | --------------------------------------------//Condition Two: When the handlebar of the bicycle, the handlebar to the wheel bracket or the car seat touches other objects//----------------------------- ---------------((ca.trigger== "destroy_bicycle" && cb.name!= "bicycle") | | (ca.name!= "Bicycle" && cb.trigger== "Destroy_bicycle"))) {//Remove all joints on the bike to achieve the destroyed bike for (var i in L) {var Jo = l[i];//Remove Joint LStage.box2d.world.DestroyJoint (JO);// Set the game end controller to the end of the game World.gameovercontroller = true;} Remove all joints from the list of bicycle joints l.length = 0;//Add game end hint var gameovertext = new Ltextfield (); gameovertext.text = "Game Over"; Gameovertext.size = 50;gameovertext.alpha = 0;gameovertext.x = (lstage.width-gameovertext.getwidth ()) *0.5;gameovertext.y = ( Lstage.height-gameovertext.getheight ()) *0.5;addchild (Gameovertext); Ltweenlite.to (Gameovertext,5,{delay:1.5,alpha:1});};

The function will accept a parameter, what is the parameter of the object? In fact, I do not know, anyway, there are getfixturea and Getfixtureb these two functions. These two functions can take the shape of the rigid body that is colliding, take the B2body object through the GetBody, and then take the B2body Getuserdata to the final Lsprite object.

I'm going to introduce the execution logic of this function. First, if the game is finished or jointlist an empty array, the subsequent code is no longer running, and if you continue to run the code, you first take the lsprite of the two rigid bodies that collided, and then the game is over, and if you pass the game, the end of the code is executed. Someone may wonder what that world is? If you look at the first chapter, you should understand. The main is Postsolve is a callback function, the inside of this is not pointing to main.


In that 19-line judging condition, I set two conditions to satisfy one of these two conditions, and then destroy the joint: condition one: When the bicycle and the wall collide; condition two: When the handlebars of a bicycle, the handlebar to the wheel, or the seat of a car touch other objects.

The destruction section of the code is mainly to note that in the box2d, the destruction of the joint with Destroyjoint this function, which in the "crushing principle" has been mentioned, this function is in the B2world class, the lbox2d world property is the B2world instantiation of the object.

The key to the game is to see the name and trigger of the Lsprite object where the collision is b2body (the meaning of "trigger" in English translation), where are these properties set? Of course it's in the class bicycle class that constructs bicycles. Let's take a look at the added & improved code in the Bicycle class.

First, let's look at the change of Bicycle's init function:

Bicycle.prototype.init = function () {var s = this;var SX = S.sx;var sy = s.sy;/** wheel radius */var WHEELR = 20;/** distance between wheels */var gap Betweenwheelandwheel = 100;/** car handle to wheel distance */var Gapbetweenwheelandhandlebar = 50;/** handlebar size */var handlebarwidth=20, handlebarheight=5;/** seat to wheel bracket distance */var gapbetweenwheelframeandseat = 30;/** seat size */var seatwidth=30,seatheight=5;/** Bracket size */var framesize = 10;/** Join bracket *///wheel bracket var frameaobj = new Lsprite (); frameaobj.x = SX+GAPBETWEENWHEELANDWHEEL/2; FRAMEAOBJ.Y = Sy+framesize/2;frameaobj.addbodypolygon (gapbetweenwheelandwheel,framesize,1,5); World.addChild ( Frameaobj); S.bodylist.push (frameaobj);//handlebar to wheel bracket var framebobj = new Lsprite (); Framebobj.trigger = "Destroy_bicycle"; framebobj.x = Sx+gapbetweenwheelandwheel-framesize/2;framebobj.y = SY-GAPBETWEENWHEELANDHANDLEBAR/2; Framebobj.addbodypolygon (framesize,gapbetweenwheelandhandlebar,1,2); World.addchild (FRAMEBOBJ); S.bodyList.push ( Framebobj);/** add handlebar */var handlebarobj = new Lsprite (); Handlebarobj.trigger = "destroy_bicycle"; handlebarobj.x = SX+GAPBETWEENWHEELANDWHEEL-HANDLEBARWIDTH/2-FRAMESIZE;HANDLEBAROBJ.Y = sy-gapbetweenwheelandhandlebar+ Handlebarheight/2;handlebarobj.addbodypolygon (handlebarwidth,handlebarheight,1,.5); World.addChild (HANDLEBAROBJ ); S.bodylist.push (handlebarobj);/** joins the seat *///seat to the support of the wheel bracket var seatframeobj = new Lsprite (); seatframeobj.x = sx+30; SEATFRAMEOBJ.Y = Sy-gapbetweenwheelframeandseat/2;seatframeobj.addbodypolygon (Framesize, gapbetweenwheelframeandseat,1,1); World.addchild (seatframeobj); S.bodylist.push (seatframeobj);//seat var SEATOBJ = new Lsprite (); Seatobj.trigger = "Destroy_bicycle"; seatobj.x = SX+30;SEATOBJ.Y = Sy-gapbetweenwheelframeandseat-seatheight/2;seatobj.addbodypolygon (seatwidth,seatheight,1,.5); World.addChild ( Seatobj); S.bodylist.push (seatobj);/** Join wheel *///left wheel Avar wheelaobj = new Lsprite (); wheelaobj.x = Sx-wheelr;wheelaobj.y = Sy;wheelaobj.addbodycircle (wheelr,wheelr,wheelr,1,2.5,.2,.4); World.addchild (wheelaobj); S.bodyList.push ( Wheelaobj)///Right wheel Bvar wheelbobj = new Lsprite (); wheelbobj.x = Sx+gapBETWEENWHEELANDWHEEL-WHEELR;WHEELBOBJ.Y = Sy;wheelbobj.addbodycircle (wheelr,wheelr,wheelr,1,2.5,.2,.4); World.addchild (wheelbobj); S.bodylist.push (wheelbobj)/** add joint *///wheel A and wheel support swivel joint World.jointList.push ( LStage.box2d.setRevoluteJoint (Frameaobj.box2dbody, Wheelaobj.box2dbody));//swivel Joint World.jointList.push wheel B and wheel support ( LStage.box2d.setRevoluteJoint (Frameaobj.box2dbody, Wheelbobj.box2dbody));// The handlebar to the wheel bracket and the welded joint of the wheel bracket World.jointList.push (LStage.box2d.setWeldJoint (Frameaobj.box2dbody, Framebobj.box2dbody));// The handlebar to the wheel bracket and the handlebar weld Joint World.jointList.push (LStage.box2d.setWeldJoint (Handlebarobj.box2dbody, Framebobj.box2dbody));// The wheel supports and seats are welded joint World.jointList.push (LStage.box2d.setWeldJoint (Seatframeobj.box2dbody, Frameaobj.box2dbody));// Seat bracket and seat welded joint World.jointList.push (LStage.box2d.setWeldJoint (Seatframeobj.box2dbody, Seatobj.box2dbody));/** Traverse all bike Parts rigid body */for (var key in s.bodylist) {var obj = s.bodylist[key];//Add mouse drag if (obj.box2dbody) Obj.setbodymousejoint ( true);//Set object name Obj.name = "Bicycle";} /** setting the primary rigid body */s.mainbody = Frameaobj.box2dbody;/** set pull-pressure operation rigid body */s.tcbody = wheelbobj.box2dbody;}; 
The main change is here:

/** Add joint *///wheel A and wheel mount swivel joint World.jointList.push (LStage.box2d.setRevoluteJoint (Frameaobj.box2dbody, Wheelaobj.box2dbody));//wheel B and wheel support swivel joint World.jointList.push (LStage.box2d.setRevoluteJoint (Frameaobj.box2dbody, Wheelbobj.box2dbody))///handlebar to wheel bracket and wheel bracket welded joint World.jointList.push (LStage.box2d.setWeldJoint (Frameaobj.box2dbody, Framebobj.box2dbody)),//handlebar to wheel bracket and handlebar weld joint World.jointList.push (LStage.box2d.setWeldJoint (Handlebarobj.box2dbody, Framebobj.box2dbody)///wheel bracket and seat welded joint World.jointList.push (LStage.box2d.setWeldJoint (Seatframeobj.box2dbody, Frameaobj.box2dbody)///seat bracket and seat welded joint World.jointList.push (LStage.box2d.setWeldJoint (Seatframeobj.box2dbody, Seatobj.box2dbody));
I added all the joints to WOLRD's jointlist so that we could traverse the joints and destroy them, which was done in Main's postsolve.

Also modified is: 1, to all of the rigid body belonging to the bicycle is added a name attribute, set as: "Bicycle", 2, to the key parts of the rigid body (handlebar, handlebar to the wheel of the carriage and saddle) added the trigger property, set to "Destroy_bicycle", Indicates that if these parts meet other rigid bodies that do not belong to bicycles, they will end the game.

As for the rigid body named "Wall", there is actually only one (Bottomborder bottom border, which ends the game when the bike falls to the end):

Main.prototype.addBorder = function () {var s = this;/** Create border *///set Border size var bordersize = 10;//Top border var topborder = new Lsprite ( ); topborder.x = S.scenewidth/2;topborder.y = 5;topborder.addbodypolygon (s.scenewidth,bordersize,0); S.addChild ( Topborder)///Right border var rightborder = new Lsprite (); rightborder.x = S.scenewidth-5;rightborder.y = S.SCENEHEIGHT/2; Rightborder.addbodypolygon (bordersize,s.sceneheight,0); S.addchild (rightborder);//Bottom Border var bottomborder = new Lsprite (); bottomborder.name = "Wall"; bottomborder.x = S.scenewidth/2;bottomborder.y = s.sceneheight-5; Bottomborder.addbodypolygon (s.scenewidth,bordersize,0); S.addchild (bottomborder);//left border var leftborder = new LSprite (); leftborder.x = 5;leftborder.y = S.sceneheight/2;leftborder.addbodypolygon (bordersize,s.sceneheight,0); S.addchild (Leftborder);};
Ok, run the code and get the results shown in the top image of this article.


Bong Source code: Http://files.cnblogs.com/yorhom/box2dBicycle%283%29.rar

Test Address: http://game.hdc.h5stars.com/201428053f36b0853f15~

This series of tutorials to this address, in fact, if you want to do a real "off-road mountain bike" this game, but also need to map the rigid body, victory judgment and so on. These are very simple, you can do it by yourself ~ (at present I do the demo should be used as a vent tool bar, pressure, to take this virtual bike to the hard to fall bar ~ haha)


This chapter is the first to come here. If there is any omission in the article, please correct me. Of course, there is no understanding of the place also welcome you to leave a message at the bottom of this article, I will try to reply to you.

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

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

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.