HTML5 game development Combat--attention point

Source: Internet
Author: User
Tags event listener

1.WebSocket is part of the HTML5 standard that Web pages can use to permanently connect to the socket server. This interface provides an event-driven connection between the browser and the server, which means that the client does not have to send a new data request to the server every other time period. When the data needs to be updated, the server can push the data directly to update the browser. One of the benefits of this feature is that players can interact with each other in real time. When a player does something, it sends the data to the server, and the server broadcasts an event to all the other connected browsers, letting them know what the player has done. This makes it possible to make HTML5 online games.

2. With the native support for HTML5 elements in modern browsers, it is no longer necessary for users to pre-install third-party plugins to play the game.

3. We place the JavaScript code before the body end tag </body> and after all the content on the page. Here's why you put your code in this position, not between the previous

4. Typically, browsers load and render content from top to bottom. If the JavaScript code is placed in the head section, the JavaScript code is loaded and the contents of the document may not have finished loading. In fact, if the browser loads JavaScript code in the middle of the page, it interrupts the rendering and loading in progress. That's why it's possible to put JavaScript code at the bottom of the page. In this way, the performance of the loaded content can be improved.

5.jQuery gives us a way to execute code after the page has been loaded, as follows:

JQuery (document). Ready (function ()

{

Here is the code

});

$ (function ()

{

Here is the code

});

6. There are several advantages to using jquery than simply using javascript:

Using jquery, you can select and modify DOM nodes with shorter code.

Short code is more useful for code reading, which is important for game development because game development often involves a lot of code.

Writing short code can speed up development.

Using the jquery library allows the code to support all major browsers without additional adjustments, and jquery wraps the pure JavaScript code to achieve its own cross-browser capabilities.

7. Assign a number to each key on the keyboard, and by getting the number, we can find out which key is being pressed. By listening to JQuery's KeyDown event listener, the event object will contain the key code when it is triggered. The key code can be obtained by invoking the which function of the key event object.

$ (document). KeyDown (function (e)

{

Console.log (E.which);

Switch (E.which)

{

Case 38://Press the UP key to handle

}

});

8. In most cases, CSS styles can be set for the left and top properties of DOM elements in a format such as 100px. The units are specified when the property is set, and when the property value is obtained, the value returned is the unit of the band. For example, when you call $ ("#paddleA"). CSS ("top"), the resulting value is 100px instead of 100. This will cause problems when performing mathematical operations on this value.

$ ("#paddleA"). CSS ("top") + 5, the return will be 100px5, not the result we want.

9.parseInt (String, radix) a string to parse, an optional parameter that indicates what system needs to be used in a number.

Parse ("5cm") returns 5; Parse ("FF", 16) returns 255

10. Because global variables are valid throughout the document, the probability of variable name collisions increases when different JavaScript libraries are integrated into a Web page. A better approach would be to put the global variables used in an object.

11. Before you introduce the back visibility, all of the elements on the page should only be presented before them. Previously, the element had no concept of front or back because it had only one choice. Now, when CSS3 introduces a three-axis rotation concept, the element can be rotated 3D so that it has a back side.

12.CSS3 refers to a property called backface-visibility (back visibility) that defines whether you can see the back of the element. By default, it is visible.

13. Align

$ ("#cards"). Children (). each (function (index)

{

Align the cards in the form of 4x3

$ (this). CSS (

{

' Left ': ($ (this). Width () +) * (index% 4),

"Top": ($ (this). Height () +) * Math.floor (INDEX/4)

});

});

"%" is called the modulo operator in JavaScript, which returns the remainder of the dividend. The remainder is used as a count of columns; The result of division--quotient, can be used as a count of rows.

With the index value 3 as an example, 3%4 equals 3, so a card with an index value of 3 is in column 4th. and 3/4 equals 0, so it's on line 1th.

14.CSS3 Flexible Box Layout module

Display:-webkit-box;

-webkit-box-pack:center;

-webkit-box-align:center;

The Elastic box module defines the alignment of elements when there is extra space in the container of the element. We can set the behavior of the element as an elastic box container: Set the value of display (a CSS2 property) to Box (a CSS3 new property value). Box-pack and Box-align are two properties that define how to align and use additional free space in both horizontal and vertical directions. You can center an element by setting two properties for center.

15. Custom Data properties allow you to save your custom data in a DOM element. We can create a custom property name prefixed with data-and assign it a value.

<ul>

< li Data-chapter = "2" data-difficulty = "Easy" > Ping-Pong </li >

< li Data-chapter = "3" data-difficulty = "Medium" > Matching Game </li >

</ul>

This is a new feature proposed in the HTML5 standard. According to the web site, the purpose of custom data properties is to save the page or application's private custom data, currently, no other attributes and elements are more appropriate for this purpose.

The website also says that this custom data property is "a common extension mechanism for Web site-only scripts to use instead of common metadata."

$ (this). attr ("Data-pattern", pattern);

For HTML5 custom Data properties, jquery provides another function to access the HTML5 custom attribute property, which is the data function.

The data function is first used to embed custom data for the jquery object of an HTML element. Later used to access the HTML5 custom data properties.

. data (key);

. Data (key, value);

< div ID = "target" data-custom-name = "HTML5 Games" > </div > You can call jquery's data function to access the Data-custom-name property

$ ("#target"). Data ("Customname") it will return "HTML5 games"

One of the most important features of 16.HTML5 is the canvas element. We can think of the canvas element as a dynamic area that can be used to draw images and graphics inside a script.

17. Perform path drawing operations in the canvas

var canvas = document.getElementById ("game");

var ctx = Canvas.getcontext ("2d");

Ctx.fillstyle = "Red";

Ctx.arc (0, Math.PI * 2, true);

Ctx.fill ();

Ctx.arc (0, Math.PI * 2, true);

Ctx.fillstyle = "green";

Ctx.fill ();

When you call an arc function or other path-drawing function, the path is not drawn immediately on the canvas. Instead, just add it to a list of paths. These paths are not drawn until the drawing command is executed.

There are two drawing execution commands in the canvas's API, one for populating the path and the other for drawing strokes. You can fill the path with the fill function, and you can stroke the path by calling the stroke function.

The fill and stroke functions are responsible for populating and drawing paths on the canvas, but it is not responsible for clearing the list of paths. The above example fills the circle with red, adds another circle and fills it with green, and the result is two circles filled with green. Because the list of paths in the canvas contains two circles when the 2nd Fill command is called. Therefore, the fill command fills the two circles with green, which is to repopulate the circles used for red.

To solve this problem, you need to make sure that you call Beginpath before you draw a new shape. Beginpath clears the list of paths, so the next time you call the fill and stroke commands, it will only apply all paths after the last call to Beginpath. The Closepath function draws a straight line from the end of the latest path to the beginning of the path, which is used to close the path.

18. In JavaScript, you can use the Math.random () function to generate random numbers.

The random function has no arguments, and it always returns a floating-point number between 0~1, which is greater than or equal to 0 and less than 1. There are two common ways to use the random function. One is to generate random numbers within a given range. The other is to generate a Boolean value of TRUE or false.

Math.floor (Math.random () * B) + A; The Math.floor () function gives away the decimal number of a given digit. Math.floor (Math.random () * 10) + 5 is an integer between 5~14;

(Math.random () > 0.495); Gets a random Boolean value that means that there will be 50% return false and 50% returns TRUE.

19. It is worth noting that the text drawn in the canvas is treated as bitmap image data, which means that the browser cannot select the text, and the search engine cannot index the text; For this reason, we should consider whether the text is drawn in a canvas or placed directly in the DOM.

20. Play the sound. You can get a reference to the audio element by calling the getElementById function. Next, call the play function to play it.

< Audio id = "Buttonactive" >

< source src = "Media/button_active.mp3"/>

< source src = "Media/button_active.ogg"/>

</audio >

< script >

document.getElementById ("Buttonactive"). CurrentTime = 3.5;

document.getElementById ("Buttonactive"). Play ();

document.getElementById ("Buttonactive"). Pause ();

</script >

The play function plays the audio from the current playback time, which is stored in the CurrentTime property. The default value for CurrentTime is 0. The above code will start playing audio from 3.5 seconds, and you can pause the playback of an audio element by using the pause function.

The second parameter of the parseint function of 21.JavaScript is optional. It defines the cardinality of the parsed number. By default, it uses decimal, but when the string starts at zero, parseint parses the string in octal. For example, parseint ("010") returns 8 as a result instead of 10.

22. Save and load data via local storage technology. You can use the SetItem function of the Localstorage object to hold the data.

Localstorage.setitem (key, value); The key is the name of the record, used to identify the corresponding entity, and the value is any data that will be saved.

Localstorage.getitem (key); the function returns the stored value of the given key. When you try to get a nonexistent key, it returns NULL.

23. Size limit for local storage. Each domain name is limited in size when it stores data through Localstorage. This size limit may be slightly different in different browsers. Typically, the size limit is 5MB. When a key-value pair is set to Localstorage, the browser throws an Quota_exceeded_err exception if the limit is exceeded.

24. Using SetItem and GetItem

Localstorage.setitem ("Last-elapsed-time", elapsedtime);

var lastelapsedtime = Localstorage.getitem ("Last-elapsed-time");

To access Localstorage as an array, the code is as follows:

localstorage["last-elapsed-time"] = ElapsedTime;

var lastelapsedtime = localstorage["Last-elapsed-time"];

25. Modern Web browsers natively support JSON, using the Stringify function can easily encode any JavaScript object into JSON, the code is as follows: Json.stringify (Anyobject);

26.localstorage.removeitem (key); Use this function to remove the use of records for a given key;

27.localstorage.clear (); Use this function to delete all records.

28.WebSocket allows the creation of an event-driven server-client architecture that allows all connected browsers to deliver messages in real time to each other.

29. Broadcast messages to all connected browsers. Whenever a new connection event is triggered by the server, updates to the number of connections are broadcast to all clients. It is very easy to broadcast a message to the client, just call the broadcast function of the server instance and pass the string type of broadcast message as a parameter to the function.

The following code snippet is used to broadcast a server message to all connected browsers:

var message = "A message from server";

Server.broadcast (message);

30. Messages sent and received between the server and the client can only be of type string and cannot be sent directly to the object. Therefore, you can convert the data to a JSON-formatted string before transferring it.

31. You can use the following CSS styles to move these image label resource locations out of the HTML display to achieve the purpose of hiding them. We don't use Display:none to do this because the browser cannot get the length and height of the element that is not displayed. In the physical world, it takes length and height to correctly position the image:

#asset

{

Position:absolute;

top:-99999px;

}

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.