Native JS Canvas Collision game Development Notes

Source: Internet
Author: User

-----------------------------------------------Welfare---------------------------------------------

-----------------------------------------------Split Line---------------------------------------------

Today we're studying the crash game.

What is a collision game? Of course, things come together. With the front-end logic, it's the event that 2 objects collide with one another.

Ask how useless first sweep down the two-dimensional code experience (happy bucket landlord to pick up the Lantern festival)

Very simple also very practical collision bar (although also very boring)

But my idea is that a collision game can be written using a game engine like cocos2d or Createjs. But the only one who calls me is native JS and jquery Zepto ha

I try to write this game and share ideas with you.

First of all, this is not my first time to write a collision game. But previously written collision games are the DOM method generated by the overall very card! Card!

This time change to canvas to do. It was very smooth.

My basic idea is that the game flow is an object, the game of dynamic elements (props characters) is an object, the game of static elements (background decorations) is the DOM element

Then this creates a background with div and so on. Use the canvas DrawImage method to produce the glutinous rice balls and the like

Dom this piece I don't have to. Right-click on the source to know how to layout the main want to analyze the canvas generated

The so-called fall in canvas is not as simple as animate linear change

It splits several blocks to create elements to insert elements in the update element loop: People who are familiar with frame animations are more familiar with the animations we see that are made up of countless small variations of animations!

The smaller the animation the smoother this is what we often say fps. (Playing game card)

_createcavaseele:

This method is designed to create elements. Of course it should be called creating objects better. Because the element is just an IMG, it's impossible to move judgment.

Steinsgate (the name is very bright) is a constructor returns 1 element objects This object contains some of the necessary properties corresponding to the logical judgment behind it!

1 varSteinsgate=function(pic,type) {2     if(!pic) {return"Undefined";}3     varthat= This;4      This. tag=pic[0];5      This. img=NewImage ();6      This. src=pic[1];7      This. width=pic[2];8      This. height=pic[3];9      This. x=pic[4];Ten      This. y=pic[5]; One      This. lastx= This. x A      This. lasty= This. Y; -      This. collide=false; -      This. down=false; the  -     if(type== "Dom") {//Dom Generation -         if(!document.getelementbyid ( This. Tag)) { -             varFarmer=document.createelement ("div"); +}Else{ -             varFarmer=document.getelementbyid ( This. tag); +         } AFarmer.id= This. Tag; atFarmer.classname= This. Tag; -farmer.style.left= This. x+ "px"; -              -farmer.style.top= This. y+ "px"; -              -$ (". Lovelive"). append (farmer);  in     } -     Else{//Canvas Build to          This. loadimg=function(){ +That.img.src=that.src; -That.img.onload =function () {         the_this._updateele (That, This. x, This. y);//_this is a closure, pointing out the collidegame. *             } $                 Panax Notoginseng         }(); -     } the      +}

It was originally built only by canvas, but it was also cleared by the farmer when the image was cleared so the farmer is the object of the data or the canvas data image is generated by the DOM

I wonder if you have a better way? Don't write 2 canvas tags oh, break the beauty of the layout.

_ctrlgame

This method is the main logic program of the game;

Add basic attributes (dumplings or king-fried) basic events (control or drop) for each element you just created

and global control game process _ctrldownitem (Control drop) _ctrlfarmer (control farmer)

Note that this method is still not generating images in the canvas. The build is in control of the called _updateele method

_ctrldownitem and _ctrlfarmer

Load the set parameters and layout properties (Canvas high AH canvas wide AH) and corresponding events for the object's bindings (falling words bound collision landing or control touch event)

In these correspondence, there are logical judgments of various details.

_iscollide and _isground and _canvas_touchmove

These are the details of the logical judgment of the specific principles, see the source is worth mentioning is to come up touchmove I always coordinate not study half a day originally found that the phone screen size and page wrap size is not 1:1 after the equivalent conversion can be solved

After these judgments, the last update canvas _updateele (note that there is still no image generated!!) )

_updateele

The principle is very simple only meet the conditions of the ability to generate images of all the conditions in the above judgment has been effective!!

Don't forget that the canvas's Clearrect method first clears the last remaining image from the new drawing

1 //Update Element POS2_updateele:function(Ele,x,y,type) {//ele: element x: X coordinate of the element y: the y-coordinate of the element type: Drawing method (default)3               if(type== "Dom"){4                       //update x coordinate;5                       6                       if(x) {ele.x=x;}7                       //Update the y-coordinate;8                        if(y) {ele.y=y;}9                        Tendocument.getElementById (Ele.tag). style.left=ele.x+ "px";//Update Image Onedocument.getElementById (Ele.tag). style.top=ele.y+ "px"; AEle. lastx=ele.x; -Ele. lasty=ele.y; -}Else{//Canvas the _this.ctx.clearrect (ele. LASTX, Ele. Lasty,ele.width,ele.height); -                           //the following conditions are sufficient to draw -                        if(ele) {//whether there are elements -                          if(!ele.down) {//Whether it has landed +                              if(!ele.collide) {//whether a collision occurred -                                     //update x coordinate; +                                     if(x) {ele.x=x;} A                                     //Update the y-coordinate; at                                      if(y) {ele.y=y;} - _this.ctx.drawimage (ele.img,ele.x,ele.y,ele.width,ele.height); -Ele. lastx=ele.x; -Ele. lasty=ele.y; -                                 } -                             } in                        } -                         to                        +                 } -                  the},


At this point the entire game function is constructed and the next step is to control the principle of each parameter or the old

Create Object-"Insert Object-" Update object (only images are eligible)

When the object's activity is over, don't forget the garbage collection =null.

But I'm not sure if this is a good way to see this,

Makikulisi () My principle is to split the entire animation of the element's motion into a lot of frame and then recursively settimeout (16 milliseconds) to refresh the frame to achieve the frame animation effect

Maybe there's a better way in the game frame?

Iscollide () I started with the old method (this old method I studied for a full 1 days!!) But it looks like there's an amazing Ispointinpath method on the web, and it works.

Because it is too magical and the old way of bitterness so I am also very doubt this is not a bug?

In short, the entire production process itself is incredible I just wrote when I still think I can not write it (no frame!) )

But write it and write it. It's the ship to the bridge, naturally straight.

Hope that you later make this type of game to help not afraid of native JS can also write!

Attached source

 

  

Development notes for native JS canvas Collision games

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.