H5 tank battle "player controls tank movement"

Source: Internet
Author: User

Since 45+11+11 cut down the size of the large three pairs, the online emergence of a variety of divine jokes, one is this: Wei: Hey, man, how have you been recently!  Eyebrows: The other side turned on the friend verification, please add the other side as Friends Wei Less: ... Jrs:2333333 saw a match on the day of data statistics: Wei 45+11+11, du Shao 32+8+3, Ibaka 19+11+2, Reggidjeckson 17+3+6, Harden 16+6+16, Thunder Management really should be renamed Lei Feng management team,  Now the daily round of the Thunder management is the norm for the JRS. Well, no, and then on a blog (H5 tank Battle of the Tank http://www.cnblogs.com/zhouhuan/p/H5_tankgame.html), this article to see how to respond to the player's operation to allow the tank to move accordingly. 1. Understanding the KeyDown eventKeyDown the trigger condition for this keyboard event is to press any key on the keyboard, and if you press and hold, the trigger will be re-sent. Example:
function () {    alert ("Merry christmas! ");};
When the page is loaded, the Merry christmas! will pop up regardless of which key is pressed "Pop-up window. 2. Understanding key codes and character encodings ① Key CodeWhen the KeyDown and KeyUp events occur, the KeyCode (key) property of the event object contains a code that corresponds to a specific key on the keyboard. For the alphanumeric character set, the value of the KeyCode property is the same as the encoding of the corresponding lowercase letter or number in the ASCII code. The capitalization of the letters does not affect.
function (Eve) {    alert (eve.keycode);};
By pressing any key on the keyboard, you can get the corresponding keycode of the key. ② character encodingWhen the KeyPress event occurs, the CharCode property of the event object contains a value that is the ASCII encoding of the character represented by the pressed key, and the character encoding of the same letter is not the same. Note that the KeyPress event is triggered only when the character key is pressed, not all keystrokes, such as CTRL, ALT, and so on, do not trigger the event. 3. Warm-up session ① Get the player's instructionsLet's take a look at how to get the player's command, here we write a code:
function (Eve) {    alert ("The key code corresponding to the keys is:" + Eve.keycode);}    ;
  You can run a little bit to know the key code for each button on the keyboard, and then take the button you need to continue to write programs.  What is needed here is the direction of the key up and down, of course, this can be found on the Internet, but also very convenient. After we run, we will find that the corresponding key codes are 38, 40, 37, 39, respectively.  Considering that some players are accustomed to using W A S D to operate, we can also do these keys, the keys corresponding to the key codes are 87, 65, 83, 68. OK, now that we know these things, we can write the following code:
 Window.onkeydown = function   (Eve) {   if  (eve.keycode = = | | eve.keycode = 87  else  if  (Eve.keycode = = 40 | |    Eve.keycode = = 83 under " else  if  (Eve.keycode = = 37 | |    Eve.keycode = = 65 "left"  else  if  (Eve.keycode = = 39 | | Eve.keycode = = 68 "right" 
At this point, depending on the player's operation, the corresponding direction of the text can be ejected. Given the slightly higher number of conditional branches for the IF statement above, we'd better rewrite the above code with the switch statement, which will improve performance as follows:
Window.onkeydown =function(Eve) {Switch(eve.keycode) { Case38:         Case87: Alert (On);  Break;  Case40:         Case83: Alert (Under);  Break;  Case37:         Case65: Alert (Left);  Break;  Case39:         Case68: Alert (Right); }};

   ② Package painting of tank functionsThe code of the tank that we wrote earlier is actually process-oriented, and we'll bring it over to the bar to do it in a package:
functionDrawtank (x, y) {varMyCanvas = document.getElementById (' Floor '); varCXT = Mycanvas.getcontext (' 2d '); Cxt.fillstyle= "#542174"; Cxt.fillrect (x, Y,20,65); Cxt.fillrect (x+70,y,20,65); Cxt.fillrect (x+23,y+10,44,50); Cxt.fillstyle= "#FCB827";    Cxt.beginpath (); Cxt.arc (x+45,y+35,16,0,2*math.pi,false);    Cxt.closepath ();    Cxt.fill (); Cxt.strokestyle= "#FCB827"; Cxt.linewidth= "8.0"; Cxt.moveto (x+45,y+35); Cxt.lineto (x+45,y-25); Cxt.stroke ();}
This function calls two parameters (x, y), which represent the x-coordinate and y-coordinate of the upper-left corner of the tank, respectively. Once packaged, you can create a tank anywhere you call it:
Drawtank (150,200);        // Make a tank with a point (150,200) for the upper left corner of the tank (upper left corner of the left track)
③ Understanding the Clearrect () methodThere is a previously missing knowledge Point Clearrect () method, which is the key to the game, which empties all the pixels within the specified rectangle, passes four parameters (x, y, width, height), the first two parameters represent the upper-left coordinate of the rectangle to be cleared,  The latter two parameters represent the width height of the rectangle to be cleared. For example, let's draw a rectangle first:
var mycanvas = document.getElementById (' floor '); var cxt = Mycanvas.getcontext (' 2d '= "Orange"; Cxt.fillrect (50,50,300,80);


Let's add the following line of code to run:
Cxt.clearrect (0,0,800,500);
You will find that the whole canvas is empty again because we have removed all the pixels from the canvas. 4. Warm-up completed, officially startedWarm up in front of the heat for so long, I believe you can already write a player according to the operation of the mobile tank. We try to write each process in object-oriented thinking, with the following code:
//encapsulates a function that gets the drawing environmentfunctiongetcxt () {varMyCanvas = document.getElementById (' Floor '), Mycontext= Mycanvas.getcontext (' 2d '); returnMycontext;}//encapsulates the function of a picture tank, passing two parameters x, Y, representing the horizontal ordinate of the upper left corner, respectively .functionDrawtank (x, y) {varCXT =getcxt (); Cxt.fillstyle= "#542174"; Cxt.fillrect (x, Y,20,65); Cxt.fillrect (x+70,y,20,65); Cxt.fillrect (x+23,y+10,44,50); Cxt.fillstyle= "#FCB827";    Cxt.beginpath (); Cxt.arc (x+45,y+35,16,0,2*math.pi,false);    Cxt.closepath ();    Cxt.fill (); Cxt.strokestyle= "#FCB827"; Cxt.linewidth= "8.0"; Cxt.moveto (x+45,y+35); Cxt.lineto (x+45,y-25); Cxt.stroke ();}//Initializes an object Mytank that stores properties and methods to avoid contaminating the global spacevarMytank ={};mytank.x= 350; Mytank.y= 400; Mytank.step= 3;//Set the step size, the greater the step, the faster the tank moves.//draw a tank first.Drawtank (MYTANK.X,MYTANK.Y);//encapsulates a function that updates the battlefieldfunctionUpdatefloor () {varCXT =getcxt (); Cxt.clearrect (0,0,800,500);//clear the canvas before updatingDrawtank (MYTANK.X,MYTANK.Y);//once the tank has been cleared, the tank must be moved in real time to re-create it according to the coordinates .}//set a function called intermittently, update the battlefield every 100msSetInterval (function() {Updatefloor ();},100);//respond to the player's operation instructionsWindow.onkeydown =function(Eve) {Switch(eve.keycode) { Case38:         Case87: Mytank.y-= Mytank.step;//y-coordinate decrease up move             Break;  Case40:         Case83: Mytank.y+ = Mytank.step;//y-coordinate increase downward move             Break;  Case37:         Case65: mytank.x-= Mytank.step;//x-coordinate to move left             Break;  Case39:         Case68: mytank.x+ = Mytank.step;//increase x coordinate to move right    }}; 
All necessary instructions have been written in the comments.  After this, we found that the tank has been able to move up and down with the player's buttons, but there is still a problem, the tank movement is very stiff, no matter which direction the head is always facing up, we have to do on this basis to modify.  But today first write here, the next content of the author after the next time to share to everyone! Tomorrow Monday, work to work, school also to class, big guy refueling Oh, after next week, everyone away from the dream then a step closer (\ (^o^)/) Also in this blessing all the students, hope that everyone can get a satisfaction, others envy of the results! Bless you! (Note: A person's strength is limited after all, if in the process of reading found that there is a description of inappropriate or wrong place, please feel free to correct me, I appreciate it! )

H5 tank battle "player controls tank movement"

Related Article

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.