Build your own HTML5 Star Trek!

Source: Internet
Author: User

Study HTML5 Canvas The third day, feel not satisfied, suddenly forget, so take advantage of free, ready to get a small game to play! The game should pay attention to performance, there are some logic to consider, I want to also need user-modifiable, that is, user configuration. OK, let's start our simple but interesting journey

Want to see the effect first, jump to try it!

The first step, of course, requires a canvas.

1 <  ID= "Canvas"  width= "  height="> Your browser does not support canvas</canvas>

The overall structure of JavaScript is as follows:

var defines some variables Planemovetimer aircraft mobile monitor/timer Attackenemytimer firing cannon Timer onkeydown Monitor onkeyup Monitor Drawplane draw aircraft Drawenemy draw enemies

First, some variables are predefined

1 var_keya = _keyd = _keyw = _keys = 0,//Store key State2 3Step = 8,//Aircraft Movement Rate4W = over, H = 44,//Actual Size of the aircraft5PlaneX = 133, Planey = 356,//Current location of aircraft6PLANESRC = "Feiji.png",//Aircraft Material Location7IMGW = 177, IMGH = 220,//aircraft source Map Size8 9CW = +, ch = 400,//Canvas SizeTenCanvas = document.getElementById ("Canvas"), OneCTX = Canvas.getcontext ("2d");

This game only uses an external resource, that is the picture, get the address please visit the Project GitHub location link at the bottom of this article. Jump

Two ways to see a drawing first

1 functionDrawplane (x, y) {2     varIMG =NewImage ();3IMG.SRC = PLANESRC;//aircraft Source Map address4Img.onload =function() {5Ctx.drawimage (IMG, 0, 0, IMGW, IMGH, PlaneX, Planey, W, h);6     }7 }8 functionDrawenemy () {9      for(vara=0;a<cw;a+=10) {Ten          for(varb=0;b<ch-300;b+=10) { One Ctx.beginpath (); ACtx.fillstyle = "Orange"; -Ctx.strokestyle = "BLACK"; -Ctx.strokerect (A, B, 10, 10); theCtx.fillrect (A, B, 10, 10); - Ctx.closepath (); -         } -     } +}

Pictures of airplanes must be in the OnLoad () method in order to draw the plane, the current enemy is a bunch of orange not moving bricks, through the top of the canvas to draw them out.

Next, look at two keyboard events:

1Window.document.onkeydown =function(evt) {2EVT = (evt)?evt:window.event;3     Switch(evt.keycode) {4          Case65://A5_keya = 1;6              Break;7          Case68://D8_keyd = 1;9              Break;Ten          Case87://W One_KEYW = 1; A              Break; -          Case83://S -_keys = 1; the              Break; -     } - } -Window.document.onkeyup =function(evt) { +EVT = (evt)?evt:window.event; -     Switch(evt.keycode) { +          Case65://A A_keya = 0; at              Break; -          Case68://D -_keyd = 0; -              Break; -          Case87://W -_KEYW = 0; in              Break; -          Case83://S to_keys = 0; +              Break; -     } the}

As for why to set the variable _keya, _keyd, _keyw, _keys in two events, instead of triggering the paint event directly, the reason is that the event can not be triggered at the same time by pressing two keys simultaneously, only one trigger at a time, and only after the press is pressing the key can the event be triggered, simply. , if I want to move to the top left corner, at the same time press A and W, assuming a is a little slower than W, so the plane's moving path is first move up one step and then move to the left, which is obviously not what I want, I use 4 variables to store the state of the key, press the key, set its state to 1, when the button up the time , set its status to 0, and then we use a timer to continuously read the state of these keys and update the status of the aircraft in a timely manner.

The aircraft movement timer is as follows:

1 varPlanemovetimer = Window.setinterval (function(){2     if(_keya| | _keyd| | _keyw| |_keys) {3 Ctx.clearrect (PlaneX, Planey, W, h);4_keya && (planex-=step);5_keyd && (planex+=step);6_keyw && (planey-=step);7_keys && (planey+=step);8planex>=0 | | (planex=0);9planex<= (cw-w) | | (planex=cw-W);Tenplaney>=0 | | (planey=0); Oneplaney<= (ch-h) | | (planey=ch-h); A Drawplane (PlaneX, Planey); -     } -}, 10);

Ctx.clearrect () to clear the original position of the aircraft, in order to draw the next state of the plane to prepare, but there is a big problem, it is directly clear the whole block, if the game has a background, overlap, it is not to take these things are not aircraft also emptied? Forgive me for not thinking about this question for the time being.

By judging the key state, each moving step is a pre-set step and completes the boundary processing.

Then the attack timer:

1 varAttackenemytimer = Window.setinterval (function(){2     varCannonx = Planex+math.floor (W/2); //muzzle x-axis position3     varCannony = Planey;//position of the muzzle y axis4     varTmptimer = Window.setinterval (function(){//Mobile timer for each shell5Ctx.clearrect (CannonX-1, CannonY-3, 2, 3);6Cannony-= 3;//Projectile Step Distance7         if(cannony<0){8             //penetration effect of shells9 Ctx.beginpath ();TenCtx.moveto (Cannonx, 100);//100 is the lowest position for enemy OneCtx.strokestyle = "White"; ACtx.linewidth = "4";//simulated irregular destruction, not yet implemented -Ctx.lineto (Cannonx, 0); - Ctx.stroke (); the Ctx.closepath (); -Window.clearinterval (Tmptimer);//The timer to clear the shells -         } -Ctx.clearrect (CannonX-1, CannonY-3, 2, 3); + Ctx.beginpath (); -ctx.fillstyle= "Red"; +Ctx.fillrect (CannonX-1, CannonY-3, 2, 3);//Shell size: 2X3 A Ctx.closepath (); at}, 0); -}, 500);

Every 0.5s fired a shell, each shell and set up a timer, in order to control, the movement of the shells I also use the way of the first wipe, because the projectile movement also has a step distance, the so-called shell penetration effect is directly draw a color and background color straight line just. Try to modify the projectile step distance can adjust the speed of the shells, can also adjust the size of the shells.

The last step, but also almost what, the first is to draw the enemy and aircraft!

1 Drawplane (); 2 drawenemy ();

Done! Also want to continue to optimize the increase of playability, but there is no time to get, there are many other things to learn, so this game first! Isn't it simple! Haha, embarrassed, the title is too tempting people, no way!

Other:

Online Demo: http://xzh-loop.github.io/Manji/lab/html5game/Plane.html

Visit the GitHub location for this project: Https://github.com/xzh-loop/Manji/tree/gh-pages/lab/html5game

Visit my GitHub pages:http://xzh-loop.github.io/

Build your own HTML5 Star Trek!

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.