HTML5 Game Development Tutorial

HTML5 Canvas游戏开发实战指南与项目 Canvas是一个HTML元素,它通过使用JavaScript中的Canvas API或WebGL API绘制图形和动画。要开始在Canvas上绘图,你需要先获取Canvas元素,并使用getContext方法创建一个渲染上下文。这是绘图的入口点,它允许我们访问各种绘图方法。// 获取canvas元素// 获取2D渲染上下文这个ctx对象是所有2D绘图的基础。它是一个的实例,拥有众多属性和方法,用来控制绘制的外观和行为。 阅读详情

里面写到了简单的物理系统,感觉特实用,下次做游戏的时候果断会用到


How to Make Money From Your Games (Adsense, Merchandise, etc.)

Making a game is only half the battle if you are looking to make money from your creations. Once you've made the game, you will want to think of ways to make money from it.
A lot of what I'm going to go into in this post applies to any kind of game, although I'm using HTML5 games as the focused example.

One way would be having a donate button, but personally I like to stay away from donate buttons, because it feels a bit like begging. I rather make money through giving a service to people.
There are three main services you can provide; merchandise, advertising and in-game purchases.

Merchandise: I haven't really focused on selling merchandise much, I've only set up a small store at CafePress ( SlashMerch), however I may focus more on that in the future.
Setting up a CafePress store is pretty simple, you just sign up, and pick an item, and add your artwork to it. (Note that it needs to be your own artwork, copyrighted materials is a huge no-no)

Advertising: There are many ways to go about this. The most popular way to advertise on a web page is to use Google Adsense. You just set up an account, get your site approved, then add a little block of code which generates adverts from the sites that people using adwords have created. Adwords is where people put up their sites looking for traffic, Adsense is where people put those ads on their website to give them traffic and get money in return (which the Adwords people have paid).
There are many other services similar to Adsense, but none are close to being as profitable. The only case that I would suggest you use a service other than Adsense is if you have pornographic material, or something else which goes against Google's terms.
There is one other way, which takes a lot more effort, although has potential to make more money. Making deals with people individually. This means you directly talk to someone to make a deal that you give them traffic for whatever price. The deal would specify how the traffic is given (text link/banner image/whatever).

Where to put the ads? You could put the ads around the page that the game is on (this requires the game to not be full screen). The page this article is written on has Adsense ads around the place, that is an example of where ads can go, and it applies to pages games are on too.
Another place they can go is in a pause menu. This works for full-screen games and non-full-screen games. What you'd do for that is, put the ad's code inside a  <div id="whatever" style="display: none;"></div>. This will load the ad, but it will be invisible. In the game's code, you just have to make it that when the game is paused, it makes it appear.
Example:
document.getElementById('whatever').style.display="";
Then when the game is unpaused, use:
document.getElementById('whatever').style.display="none";
Here is an example of adsense in a pause menu of a canvas game


How much money do the ads make? This is a pretty big question. It is dependent on so many different things. It would depend on what ads actually show up, which depends on both your target audience, and the topic of the game. It also depends on how much traffic you get to your site. You need hundreds to thousands of visits per day to make any amount of money. And a huge problem is that people don't trust ads any more. The ad services that aren't Adsense have put up so many scammy ads that it gave the reputation of internet ads so much shit. However, Adsense ads are very trustworthy and they very often provide quality and interesting links.


In-game Purchases: Depending on what kind of game it is, you could have things like purchasable clothes for your character, or vehicles, etc.
Firstly, you'll need to set up a database to hold usernames, encrypted passwords and what purchases have been made by whom. When you have the database set up, you will be able to have a php script that deals with it, and you can then use AJAX in your game's JavaScript which runs the script, putting in parameters like "username" and "itemtobuy".
From there it will be able to access something like PayPal to accept a payment. Then, in your game you will be able to have it check for what purchases have been made, and it can decide what things to show up.
You could also use a service specifically for In-App purchases. Such as Google In-App purchases.


It is a lot harder to make money than people think. And the best way to make sure you do make money, is to make sure your game will appeal to people. A lot of people have the wrong idea of what kind of games will appeal to people. Too many people think it just needs to be "cool", but it actually doesn't.
It needs to be addictive. And to do that, it either needs to be simple enough to just lazily do without too much thought, or complex enough that it fucks you in the mind and you just need to keep trying until you get it right.
There's a whole lot more to it than that, but I'm just giving you some food for thought.

SATURDAY, 20 AUGUST 2011

Introduction to JavaScript

It just occurred to me that I've been going on about how to make a HTML5 game, while there's people who want to make a game who haven't even started with programming/scripting at all yet.
Before you get started with games development, you're going to want to have a little bit of experience with the coding first.

So, what I'll do here is introduce you to the basics of JavaScript. I'll go into enough that will allow you to start learning to make HTML5 games.


JavaScript is not Java. This is something too many people get confused with. JavaScript is a scripting language, whereas Java is a compiled language. JavaScript is very loosely based off of the Java language.
And when I say that Java is a compiled language, what I mean by that is, once you write the code, you have to run a compiler to then get the file that you actually run as the program. Scripting languages on the other hand are run line-by-line without compiling the whole code into a file. This means all you have to do is write the code and run the program. (In JavaScript's case, you just write the code then open the web page, and it's running)



Ok so that's what JavaScript is, now let's get into how to write code.
Here is a little snippet of code, I'll then explain it:
      
<script type="text/javascript">   var string = "Hello";   function writeSomeText()      document.write(string+" World");   } </script> <a onmouseover="this.style.cursor='pointer';" onclick="writeSomeText();"> CLICK HERE </a>

So, you see the <script> HTML tags. That is where the JavaScript goes in.
The first line of JavaScript there is  var string = "Hello";
That line creates a  variable called  string, and gives it a value of "Hello". The semi-colon at the end of the line is part of the JavaScript syntax, it splits the lines up so that when the code is run, it knows how to execute it.
JavaScript is quite good with variables, because it decides itself what type a variable is. In other languages, you may have to tell it what type it is, but JavaScript automatically knows that it is a string value. And if we gave the variable a value of  500 instead of  "Hello", it would have known that it was a numeric value. However,  "500" is counted as a string.

Now, the next block of code is creating a function.
To make a function, you do  function functionName(params) { functionCode }
In my example, I didn't give it any params (parameters), but they are basically for the purpose of passing in a variable for the function to use when you call the function. I'll get to function calling later.
The function code in my example writes text to the document screen.  document is an object which holds a function called write(). It takes a parameter which the function then takes and writes to the screen.
In my example, it takes the  string variable that we set outside the function, and attaches " World" to it. It joins up to make a string value of "Hello World", but does not change the value of the variable.

Function calling: Outside the <script> tags, we see an <a> element. Since there is no href attribute given, I had to manually add the code that makes the mouse cursor change to the pointer when you mouse over the link. This was done with a line of JavaScript triggered by an event. The event was onmouseover.
The other event I used was onclick, which I used to trigger a line of JavaScript which called our writeSomeText() function. This is where the JavaScript calls up the function with that name and executes the code inside the function.


So, that's my Intro to JavaScript. It's purpose is to show you the syntax, and hopefully allow you to better understand my HTML5 game development guides.
You can move onto this  Full HTML5 Game Development Tutorial if you want.

MONDAY, 8 AUGUST 2011

HTML5 Game Development Tutorial

If you want to make a HTML5 game and just want a nice reference page you can go back to, or if you are a complete beginner and need to learn as much as possible step-by-step, then you're at the right place.

I also have a guide split into multiple pages here, if you prefer that:  HTML5 Game Development Guide.
There's also a video tutorial for the basics of HTML5 game development:  Video Intro to HTML5 Game Dev

If you don't know much about JavaScript, then have a look at the  Introduction to JavaScript.

If you want to know how to make money from your games, have a look at this article:
How to Make Money From Your Games


Contents

What is the HTML5 Canvas?
How to Draw an Image to the Canvas
How to Draw Text to the Canvas
Set up a Game Loop
Keyboard Input
Mouse Input
Add Simple Game Physics
How to Rotate an Image on Canvas
Use HTML5 Audio
Conclusion of Tutorial



WHAT IS THE HTML5 CANVAS? (BACK TO TOP)

The  <canvas> HTML element, which came to us in  HTML5 was the first step towards HTML5 games becoming big.

The canvas allows so many things that you wouldn't have been able to do otherwise, and does it rather efficiently.


Canvas renders 2D graphics onto a given area in the browser window. It does so dynamically via scripting (i.e. JavaScript). The shapes and images which are rendered on the canvas can be manipulated in several ways. The most obvious and useful ways is  rotating the image; which you would not have been able to do without the canvas, unless you did some rather inefficient and complicated php scripting to alter an image at the pixel-level to make it do a similar thing.



JavaScript has a  2D graphics API which accesses the canvas drawing area, which is how games can be written. But just because it only has a 2D API, don't let that make you think 3D isn't possible.

For a start, you could simply write your own 3D engine, which uses normal 2D functions to generate a 3D object and render the  2D projection on the canvas. Doing so just requires a bit of mathematics. But making it a huge and playable game is where it gets difficult.



You could create a whole 3D engine if you wanted, but there is a 3D graphics API available. It's called  WebGL, and it does what I just described, but it simplifies it by allowing you to just call the functions, rather than having to think up all that complicated stuff yourself. It also means that the 3D engine already has optimized code, meaning it will run faster.



HOW TO DRAW AN IMAGE TO THE CANVAS (BACK TO TOP)

This is about the simplest example of the use of HTML5 canvas you can get. This is just to show how to set up a canvas and draw in it.

Firstly, you would have this in the html of the page:

<canvas id="canvas" width="400" height="400">
Browser not compatible with HTML5 canvas
</canvas>

The id of the canvas element has been set to "canvas", which is how the javascript can identify the right canvas element to manipulate.

The width and height of the canvas will be 400px.

And if an incompatible browser is used, it will display the text "Browser not compatible with HTML5 canvas".


And here is an example of the kind of javascript you could use to draw an image (you could have this in script tags or have it in a .js file and call it from src attribute of script tags):

var canvas = document.getElementById('canvas');
var context2D = canvas.getContext('2d');

var img = new Image();
img.src = "http://www.blogger.com/img/logo40.png";
context2D.drawImage(img, 100, 50);

So first it gets the canvas element by using the id we gave it. It then creates the 2D context with that canvas element.

It then loads a new image object and then tells it to use the image from http://filevaults.com/media/Slash/553481-smiley.png by assigning it to the src variable of the Image object.



Then it uses the 2D graphics API by calling the drawImg() function.

The first parameter of the function is looking for an image object, the second is the x-position and the third is the y-position.


So here it is (I added style="background-color: #A9A9A9;" to the canvas so you can see it properly): http://slashgame.net/html5gamedevexample1.php



HOW TO DRAW TEXT TO THE CANVAS (BACK TO TOP)

context2D.fillStyle = "white";
context2D.font = 'bold 30px sans-serif';
context2D.fillText("POINTS: "+numOfPoints, canvas.width-200, 30);

That right there is an example of drawing text to the canvas. It writes it on the top right of the canvas. That particular example is what would serve as the HUD in a game.

Here it is in practise (you get points for moving right and left):  http://slashgame.net/html5gamedevexample2.php
And don't worry about the character movement code, we'll get to that very soon.

Here is a little function that draws text to the canvas with a specified position, color and font. This also shows you the different things you can do with text.
However, you may want to use this function just as a means to being able to not worry about remembering the different parts to it.
function drawCanvasText(txt, pX, pY, clr, fnt) {
 context2D.fillStyle = clr; // color
 context2D.font = fnt; // font
 context2D.fillText(txt, pX, pY); // text at position X, Y
}
Example Usage:
drawCanvasText("drawing text yas", 50, 50, "black", "bold 30px sans-serif");




SET UP A GAME LOOP (BACK TO TOP)

A game loop is the normal structure a game would be build in. This is something you would find in any kind of game, not just HTML5 games.
First it would initiate the loop (what I tend to do is trigger the initiation function when the window is loaded), then the loop would involve checking for user input, then doing what needs to be done to all the objects, then rendering/drawing the scene, and start again from checking user input.
This is an example of doing this in javascript:
const FPS = 30;

var playerPosX = 0;
var playerPosY = 0;

var playerImg = new Image();
playerImg.src = "http://filevaults.com/media/Slash/553481-smiley.png";

var canvas = null;
var context2D = null;
var keys = new Array();

window.onload = init;

window.addEventListener('keydown',keyDown,true);
window.addEventListener('keyup',keyUp,true);
function keyDown(evt){
 keys[evt.keyCode] = true;
}
function keyUp(evt){
 keys[evt.keyCode] = false;
}

function init()
{
 canvas = document.getElementById('canvas');
 context2D = canvas.getContext('2d');
 setInterval(draw, 1000 / FPS);
}

function draw()
{
 if ((37 in keys && keys[37]) || (65 in keys && keys[65])){ //left
  playerPosX -= 2;
 }
 if ((39 in keys && keys[39]) || (68 in keys && keys[68])){ //right
  playerPosX += 2;
 }
 
 context2D.clearRect(0, 0, canvas.width, canvas.height);
 context2D.drawImage(playerImg, playerPosX, playerPosY);
}

The code initiates the loop in the init() function, which is called as soon as the window is loaded up. This function uses the setInterval() function to call the draw() function 30 times per second (it uses the FPS variable to determine that frame rate).

It then adds an "event listener" for key being pressed, and for key being released. This means that when a key is pressed, it calls the function which adds the key's code to an array. When the key is released, another function is called which sets the value of that array element to false. This means that every time the loop comes to the point where it checks for user input, all it has to do is look in the array and see if it's there and that it is set to true.

Once it knows if the key is pressed, it then decides what to do with the playerPos variables. This is the stage where it changes the "virtual world".

Then the last stage of the loop is rendering/drawing the scene based on the "virtual world's" variables.
To do so, it clears the canvas fully then draws the image in the correct spot.

Here's the result of the example I just gave (use arrow keys or A and D to move left and right): http://slashgame.net/html5gamedevexample2.php


From the knowledge you have learned so far, you can make a simple game, if you have the ability to figure things out. However, I will continue and explain things in further detail and bring up new points of interest.



KEYBOARD INPUT (BACK TO TOP)

As explained in the Game Loop section of this post (just above this section); it goes through the loop, and each time, it checks if the key is pressed by checking an array to see if it is set to true or false.
An event listener calls a function when a key is pressed down, and sets the array element of the ASCII code of the key, and sets it to true. And another event listener checks for keys being released, and sets the element value to false.

Looking up ASCII values all the time can sometimes be a pain in the ass, so what I've done is made a little snippet of code you can paste into your code which allows you to simply call the function with the key you want to check as a parameter. This is simple enough to use.

Examples of use:
If you wanted to check if the A key is pressed down:
if (isKeyPressed('a')==true) { /* do whatever */ }
If you wanted to check for the left arrow key being pressed:
isKeyPressed('left')
For escape key:
isKeyPressed('esc')


The Code:
window.addEventListener('keydown',keyPressDown,true);
window.addEventListener('keyup',keyPressUp,true);

function keyPressDown(evt){
 keys[evt.keyCode] = true;
}
function keyPressUp(evt){
 keys[evt.keyCode] = false;
}


function isKeyPressed(checkKey) {
 
 // alphabet
 if ((checkKey == 'a' || checkKey == 'A') && (65 in keys && keys[65])){
  return true;
 }
 else if ((checkKey == 'b' || checkKey == 'B') && (66 in keys && keys[66])){
  return true;
 }
 else if ((checkKey == 'c' || checkKey == 'C') && (67 in keys && keys[67])){
  return true;
 }
 else if ((checkKey == 'd' || checkKey == 'D') && (68 in keys && keys[68])){
  return true;
 }
 else if ((checkKey == 'e' || checkKey == 'E') && (69 in keys && keys[69])){
  return true;
 }
 else if ((checkKey == 'f' || checkKey == 'F') && (70 in keys && keys[70])){
  return true;
 }
 else if ((checkKey == 'g' || checkKey == 'G') && (71 in keys && keys[71])){
  return true;
 }
 else if ((checkKey == 'h' || checkKey == 'H') && (72 in keys && keys[72])){
  return true;
 }
 else if ((checkKey == 'i' || checkKey == 'I') && (73 in keys && keys[73])){
  return true;
 }
 else if ((checkKey == 'j' || checkKey == 'J') && (74 in keys && keys[74])){
  return true;
 }
 else if ((checkKey == 'k' || checkKey == 'K') && (75 in keys && keys[75])){
  return true;
 }
 else if ((checkKey == 'l' || checkKey == 'L') && (76 in keys && keys[76])){
  return true;
 }
 else if ((checkKey == 'm' || checkKey == 'M') && (77 in keys && keys[77])){
  return true;
 }
 else if ((checkKey == 'n' || checkKey == 'N') && (78 in keys && keys[78])){
  return true;
 }
 else if ((checkKey == 'o' || checkKey == 'O') && (79 in keys && keys[79])){
  return true;
 }
 else if ((checkKey == 'p' || checkKey == 'P') && (80 in keys && keys[80])){
  return true;
 }
 else if ((checkKey == 'q' || checkKey == 'Q') && (81 in keys && keys[81])){
  return true;
 }
 else if ((checkKey == 'r' || checkKey == 'R') && (82 in keys && keys[82])){
  return true;
 }
 else if ((checkKey == 's' || checkKey == 'S') && (83 in keys && keys[83])){
  return true;
 }
 else if ((checkKey == 't' || checkKey == 'T') && (84 in keys && keys[84])){
  return true;
 }
 else if ((checkKey == 'u' || checkKey == 'U') && (85 in keys && keys[85])){
  return true;
 }
 else if ((checkKey == 'v' || checkKey == 'V') && (86 in keys && keys[86])){
  return true;
 }
 else if ((checkKey == 'w' || checkKey == 'W') && (87 in keys && keys[87])){
  return true;
 }
 else if ((checkKey == 'x' || checkKey == 'X') && (88 in keys && keys[88])){
  return true;
 }
 else if ((checkKey == 'y' || checkKey == 'Y') && (89 in keys && keys[89])){
  return true;
 }
 else if ((checkKey == 'z' || checkKey == 'Z') && (90 in keys && keys[90])){
  return true;
 }
 
 
 //numbers
 else if ((checkKey == '0') && (48 in keys && keys[48])){
  return true;
 }
 else if ((checkKey == '1') && (49 in keys && keys[49])){
  return true;
 }
 else if ((checkKey == '2') && (50 in keys && keys[50])){
  return true;
 }
 else if ((checkKey == '3') && (51 in keys && keys[51])){
  return true;
 }
 else if ((checkKey == '4') && (52 in keys && keys[52])){
  return true;
 }
 else if ((checkKey == '5') && (53 in keys && keys[53])){
  return true;
 }
 else if ((checkKey == '6') && (54 in keys && keys[54])){
  return true;
 }
 else if ((checkKey == '7') && (55 in keys && keys[55])){
  return true;
 }
 else if ((checkKey == '8') && (56 in keys && keys[56])){
  return true;
 }
 else if ((checkKey == '9') && (57 in keys && keys[57])){
  return true;
 }
 
 
 // special keys
 else if ((checkKey == 'left' || checkKey == 'LEFT') && (37 in keys && keys[37])){
  return true;
 }
 else if ((checkKey == 'right' || checkKey == 'RIGHT') && (39 in keys && keys[39])){
  return true;
 }
 else if ((checkKey == 'up' || checkKey == 'UP') && (38 in keys && keys[38])){
  return true;
 }
 else if ((checkKey == 'down' || checkKey == 'DOWN') && (40 in keys && keys[40])){
  return true;
 }
 else if ((checkKey == 'esc' || checkKey == 'ESC' || checkKey == 'escape' || checkKey == 'ESCAPE' ) && (27 in keys && keys[27])){
  return true;
 }
 
}


MOUSE INPUT (BACK TO TOP)

It's fairly simple to add mouse input to your game; just use an eventListener for the event "mousemove" and use a function that takes the event as a parameter (in my example below, I used mouseMoved(e)), and use the e.pageX and e.pageY for the mouse's X and Y position.

And for mouse clicks, just use eventListener for the "click" event, and use a function that does whatever. In the example I give, it sets the position of an image to the position of the mouse at the point it is clicked. In this case, a bullethole in the position the cursor was pointing at.

Here is the code:
<html>
<head>
<script type="text/javascript">
const FPS = 60;

var canvas = null;
var context2D = null;

var cursorImg = new Image();
cursorImg.src = "images/cursorexample.png";

var bulletHoleImg = new Image();
bulletHoleImg.src = "images/bullethole.png";
var bulletHolesX = new Array();
var bulletHolesY = new Array();
for (var i=0; i<50; i++) {
 bulletHolesX[i] = -500;
 bulletHolesY[i] = -500;
}
bulletNum = 0;

window.addEventListener('mousemove', mouseMoved, true);
window.addEventListener('click', clicked, true);
var mouseX = 0;
var mouseY = 0;

window.onload = init;
function init() {
 canvas = document.getElementById('canvas1');
 context2D = canvas.getContext('2d');
 
 setInterval(draw, 1000/FPS);
}

function draw() {
 context2D.clearRect(0, 0, canvas.width, canvas.height);
 for (var i=0; i<50; i++) {
  context2D.drawImage(bulletHoleImg, bulletHolesX[i]-(bulletHoleImg.width/2), bulletHolesY[i]-(bulletHoleImg.height/2));
 }
 context2D.drawImage(cursorImg, mouseX-(cursorImg.width/2), mouseY-(cursorImg.width/2));
}

function mouseMoved(e) {
 
 mouseX = e.pageX;
 mouseY = e.pageY;
 
}

function clicked(e) {
 
 bulletHolesX[bulletNum] = mouseX;
 bulletHolesY[bulletNum] = mouseY;
 bulletNum++;
 if (bulletNum > 50) {
  bulletNum = 0;
 }
 
}
</script>
</head>
<body style="padding: 0px; margin: 0px;">
 <canvas id="canvas1" width="600" height="480" style="background-color: #A9A9A9;">
 Browser not compatible with HTML5 canvas
 </canvas>
</body>
</html>
Here is the result:  http://slashgame.net/mouseinput.php



ADD SIMPLE GAME PHYSICS (BACK TO TOP)

Even the simplest physics can make a game look and feel so much better. Instead of just suddenly moving full speed to the right when you press right key, it can be that the character builds speed until they reach normal speed. It could be a case of only taking 1-2 seconds to build the speed, or it could take more like 10 seconds. It all depends on your game.
And there's gravity. There needs to be a fairly realistic rate of falling towards the ground. I don't mean close to earth's gravity, I just mean it can't just fall at a constant speed towards the ground. It needs to accelerate. (Although, this does depend on the game. There may be certain instances where a constant velocity is fine)



So let's start with a canvas of width 500x500. So that there will be room to move, to appreciate the physics a bit more.
<canvas id="canvas" width="500" height="500" style="background-color: #A9A9A9;">
Browser not compatible with HTML5 canvas
</canvas>


Now here's the javascript:
const FPS = 30;

var playerPosX = 0;
var playerPosY = 0;
var playerVelX = 0;
var playerVelY = 0;

var onGround = 0;

var playerImg = new Image();
playerImg.src = "http://filevaults.com/media/Slash/553481-smiley.png";

var canvas = null;
var context2D = null;
var keys = new Array();

window.onload = init;

window.addEventListener('keydown',keyDown,true);
window.addEventListener('keyup',keyUp,true);
function keyDown(evt){
 keys[evt.keyCode] = true;
}
function keyUp(evt){
 keys[evt.keyCode] = false;
}

function init()
{
 canvas = document.getElementById('canvas');
 context2D = canvas.getContext('2d');
 setInterval(draw, 1000 / FPS);
}

function draw()
{
 // detect user input
 if ((37 in keys && keys[37]) || (65 in keys && keys[65])){ //left
  playerVelX -= 3;
 }
 if ((39 in keys && keys[39]) || (68 in keys && keys[68])){ //right
  playerVelX += 3;
 }
 if ((38 in keys && keys[38]) || (87 in keys && keys[87])){ //up
  jump();
 }
 
 addPhysics();
 
 context2D.clearRect(0, 0, canvas.width, canvas.height);
 context2D.drawImage(playerImg, playerPosX, playerPosY);
}

function jump() {
 if (onGround == 1) {
  playerVelY -= 30;
 }
}

function addPhysics() {

 // because of these two lines, motion can be set using velocity variables
 playerPosX += playerVelX;
 playerPosY += playerVelY;
 
 
if (playerPosY > canvas.height-playerImg.height) {
 onGround = 1;
}
else {
 onGround = 0;
}

// stop character from building up too much speed
// this means the character can realistically accelerate and continue at normal speed
 if (playerVelX >= 10) {
  playerVelX = 10;
 } else if (playerVelX <= -10) {
  playerVelX = -10;
 }
 
// friction
playerVelX *= 0.85;
if (playerVelX < 0.2 && playerVelX > -0.2)
{ // so that it leaves it as a clean zero when it gets to a stop.
 playerVelX = 0;
}

 // gravity (acceleration of the velocity towards the ground)
 if (onGround == 0) {
 playerVelY += 3;
 }
 else {
 playerVelY = 0; // when on ground, gravity doesn't pull you through the floor
 }
 
}
Result here:  http://slashgame.net/html5physics.php



HOW TO ROTATE AN IMAGE ON CANVAS (BACK TO TOP)

Rotation is a tricky one to understand fully, especially for beginners. A lot of people prefer to just blindy accept the way of coding it, and other like to know what the heck they are actually coding. So I'll give the opportunity for both types of people here.

Firstly, I'll put this function here for you to use, this is helpful for any kind of person, but for those of you who just want the code, you only need to take the function and read my bit on how to use it. I'll then explain how rotation works, if you're interested.

Here's the function:
function drawImg(img, pX, pY, oX, oY, w, h, rot) {
 context2D.save();
  context2D.translate(pX+oX, pY+oY);
  context2D.rotate(rot * Math.PI / 180);
  context2D.drawImage(img, 0, 0, w, h, -(oX), -(oY), w, h);
 context2D.restore();
}

How it's used:
img: the image object
pX: the x position of the image
pY: the y position of the image
oX: how far across the image that the origin is
oY: how far down the image that the origin is
w: width of the image
h: height of the image
rot: angle of rotation


Ok, so it's not as simple as just "rotate image". There's a lot more to it. It's more like rotating the canvas, then setting the image's orientation, then resetting the canvas.

- So first it saves the canvas the way it is.
- Then the translate line makes the "start" of the image at the origin you want it to spin.
- It then rotates the actual canvas the amount you want the player to rotate.
- Then the image is drawn, but because the start of the image has changed place, it needs to start drawing at a different place (at the origin).
- It then brings the canvas back to where it was before, leaving the drawn image still showing as rotated.

It took me a while to figure that out at first. I was never able to find a good explanation of how it works. I just hope this helps you readers better.
Although to be honest, it isn't incredibly important that you know how it works. Just that you know how to use it. 
Here's an example usage of rotation with canvas:  http://slashgame.net/html5gamedevexample4.php



USE HTML5 AUDIO (BACK TO TOP)

I'll just show HTML5 Audio being used with javascript without a canvas. Using it in canvas you just include it in the javascript like normal by calling the function that plays the sound. I very much so assume that by this point you can figure that kind of thing out yourself.
The JavaScript accesses the HTML5 audio, and in effect makes an <audio> element. But it's good this way, as it's less cluttered without the tags actually being there or being created.

Example:
var boingSound = new Audio("http://slashgame.net/boing.wav");
function playSound() {
 boingSound.currentTime = 0;
 boingSound.play();
}

Notice how it sets the currentTime to 0 before playing. This is because you can't play the same sound object twice without moving the time back to the start again.


Here is a use of the result of that:
---CLICK HERE---



CONCLUSION OF TUTORIAL (BACK TO TOP)

So, by now you should be able to put your wonderful imagination to use, and put your new knowledge of HTML5 game development to practice, and create something awesome.

There may be some things that I haven't explained, but my hope is that I've explained enough so that you are able to figure new things out yourself. Things like complicated physics can be figured out with some Maths knowledge, and game design for the most part comes from your imagination and your ability to understand what people like in games.

SUNDAY, 31 JULY 2011

Another Example Site Using HTML5 Stuff

This site has a cool use of HTML5. You'll see what I'm talking about when you visit the site. It doesn't work so well on Internet Explorer (what a surprise).
Here you go:  When you see it you'll shit bricks

SUNDAY, 17 JULY 2011

Snippet List

I'll be writing a bunch of snippets for you guys to use as you please. I'm sure you will find a lot of use with them for making games, and probably other stuff too.

I'll keep this list updated when I think of more stuff to put in it. And I'm open to suggestions, if you have any, you can contact me via @SlashGame on twitter (By the way, I'm more likely to see a mention than a Private Message).



Draw Image with Rotation
Draw Text to Canvas
Play Sound (HTML5 Audio)
Mouse Input
Keyboard Input
AJAX

Snippet - AJAX

This is useful for many things with HTML5 game development. You could use it as a means to pass a user's score to a php script which adds it to a database.
Or you could do it the other way round, and make it get the highscores from the database, and the function would return the script's response, which could be used to then write the scores on the canvas, or wherever.


For Example:
ajaxCall("addScore.php?username=Slash&score=500");

That would have called the php script in addScore.php, and passed in the username and score parameters.
The php script could have simply been written to take those parameters with $_GET['username'] and $_GET['score'], and insert the values into a MySQL database.


This is just a snippet. I might later make a full tutorial on how to keep a scoreboard. But this function  will allow you to call any php script with AJAX and use it's responseText if necessary.


The JavaScript Code:
function ajaxCall(scriptURL) {
  var xmlhttp;
  if(window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
       return xmlhttp.responseText;
     }
  }
  
  xmlhttp.open("GET", scriptURL, true);
  xmlhttp.send();
}


Example PHP Script:
// set up connection
$con = mysql_connect("localhost", "DBuser","DBpass") or die(mysql_error());
mysql_select_db("DBname", $con) or die(mysql_error());

// Get params from the url used
$username = mysql_real_escape_string($_GET['username']);
$score = mysql_real_escape_string($_GET['score']);

// insert the score into the scores table for the user
$query = "INSERT INTO scores (username, score) VALUES ('" . $username . "', '" . $score . "')";
mysql_query($query, $con) or die(mysql_error());


This example PHP script will work for the stuff I mentioned earlier, calling the JavaScript function with something like  ajaxCall("addScore.php?username=Slash&score=500");

Note that this is an example to show what goes on with AJAX. However, in a professional situation, PDO would be used rather than MySQL, and jQuery would often be used in the JavaScript. Libraries are used a lot because they are already optimized code and you also have less code to write yourself.

Snippet - Keyboard Input for HTML5 Games

Examples of use:
If you wanted to check if the A key is pressed down:
if (isKeyPressed('a')==true) { /* do whatever */ }
If you wanted to check for the left arrow key being pressed:
isKeyPressed('left')
For escape key:
isKeyPressed('esc')



The Code:
window.addEventListener('keydown',keyPressDown,true);
window.addEventListener('keyup',keyPressUp,true);

function keyPressDown(evt){
 keys[evt.keyCode] = true;
}
function keyPressUp(evt){
 keys[evt.keyCode] = false;
}


function isKeyPressed(checkKey) {
 
 // alphabet
 if ((checkKey == 'a' || checkKey == 'A') && (65 in keys && keys[65])){
  return true;
 }
 else if ((checkKey == 'b' || checkKey == 'B') && (66 in keys && keys[66])){
  return true;
 }
 else if ((checkKey == 'c' || checkKey == 'C') && (67 in keys && keys[67])){
  return true;
 }

人工智能-CS188 Project 2: Multi-agents 一、项目介绍 项目介绍网页 项目代码下载 本项目是采用Berkeley的CS188课程内容实习二的内容,在这个项目中,我们将为经典版本的Pacman 设计自动算法,包括幽灵。在此过程中,我们将实现 minimax 和 expectimax 搜索并尝试评估函数设计 完成作业只需要完成5个题目,按照项目介绍的步骤进行完成,主要是在multiAgents.py文件中进行补充代码 二、代码详情 1、Question1:Reflex Agent 略 2、Question2:Minimax 套用ppt上的minm 阅读详情

相关推荐

动态博弈、威胁与承诺(博弈论入门学习笔记四)

0 动态博弈 动态博弈:行动有先后顺序,不同的参与人在不同时点行动,先行动者的选择影响后行动者的选择空间,后行动者可以观察到先行动者做了什么选择。例如下棋、消费者和商家讨价还价、谈婚论嫁、企业之间的价格战等等。 因此,为了做出最优的行动选择,每个参与人都应该思考:如果我如此选择,对方将如何应对?如果我是他,我将会如何行动?给定他的应对,什么是我的最优选择? 动态博弈中的战略:在博弈开始之前就...

stepho的博客 1万+

android sex games app,Beginning Android Games 2nd Edition

摘要:Beginning Android Games, Second Edition offers everything you need to join the ranks of successful Android game developers, including Android tablet game app development considerations. You'll sta...

weixin_42504649的博客 1万+

实战解析:利用Wireshark解密QQ通信协议

本文提供了一份利用Wireshark工具分析QQ通信协议的实战指南。文章详细介绍了从环境准备、捕获数据包到解析协议层的完整流程,重点演示了如何识别QQ号码字段、观察加密数据特征以及区分不同通信类型(如文本、文件传输)。通过此实践,读者可以深入理解网络分层模型和现代应用加密通信机制,提升网络协议分析与安全诊断能力。

weixin_29210727的博客 408

Creating 2D Games with Unity3D Part 5 Complex Collision

Way back in the first part of this series, I mentioned that you can make complex collision objects in 3D packages like Maya or Blender to ma

waleywen的专栏 2097

群晖Video Station海报墙插件更新了!手把手教你用c5h12o5插件搞定豆瓣/TMDB搜刮

本文详细介绍了如何使用c5h12o5插件为群晖Video Station配置高效的海报墙系统。该插件支持豆瓣、TMDB等多数据源并行搜刮,智能优先级设置和本地化优化,解决TMDB API失效问题,提升影视库管理体验。包含安装教程、配置策略和高级使用技巧,适合影视爱好者优化NAS媒体库。

weixin_29250403的博客 265

软件工程导论考试通关秘籍:太原理工大学历年真题解析(附答案)

本文为太原理工大学《软件工程导论》考试提供高效备考指南,通过解析近六年真题,揭示高频考点如软件生命周期、UML建模和结构化设计等核心模块的命题规律。文章提供真题拆解、实战策略和避坑指南,帮助考生掌握图形转换题和简答题的应答技巧,助力考试通关。

weixin_29233333的博客 227

Lou's Pseudo 3d Page v0.91

这篇文章写的不错,有对伪3D有兴起的朋友可以读一下。Lous Pseudo 3d Page v0.91(C) 2010 Louis Gorenfeld, updated November 10, 2010NEW: Quickie QBasic source of a simple road demonstration

shark0001的专栏 7万+

Kali Linux实战:5分钟复现永恒之蓝漏洞攻击(附Win7靶机配置指南)

本文提供了一份详细的Kali Linux实战指南,指导读者在5分钟内于隔离的虚拟环境中复现经典的永恒之蓝漏洞攻击。内容涵盖从Windows 7靶机配置、网络设置,到使用Nmap进行服务发现、利用Metasploit框架进行漏洞扫描与利用的全过程,并演示了基础的Meterpreter后渗透操作,旨在帮助网络安全学习者通过亲手实践深入理解SMB协议漏洞的攻防原理。

weixin_29313547的博客 196

Building a 3D Game in XNA From Scratch - Free Video Tutorial Series Now Available!

 After far too many hours of learning, teaching, recording, testing, video editing, and other glorious activities, I am ready to make available my massive collection of video tutorials for creatin

0.5 Degree 26万+

GEE:关于遥感生态指数(RSEI)的若干疑问

本文记录了若干关于在 Google Earth Engine (GEE)平台上,计算基于主成分分析(PCA)的遥感生态指数(RSEI)的问题。并记录了解决这些问题的一些答案。问题包括,主成分分析的特征值的正负,主成分的占比,去云后空值像素的处理方法,异常值处理方法,如何看载荷等。

养乐多的博客 3417

D16: OpenClaw + Notion API:知识管理新玩法

本文介绍了如何利用OpenClaw连接Notion API构建自动化知识管理系统。文章首先分析了传统知识管理的痛点,包括信息分散、更新不及时等问题,并对比了Notion与其他工具在API完整性、结构化程度等方面的优势。接着详细说明了Notion API的获取和授权流程,并设计了包含项目知识库、技术决策库和会议纪要库的三层架构系统。最后通过会议纪要自动归档的实战案例,展示了如何通过YAML配置实现从飞书会议到Notion的自动化知识沉淀流程。该方案能有效解决团队知识管理中的信息碎片化问题,提升协作效率。

刘一说的IT专栏 274

欧美html游戏安卓,HTML5 Games - Rated M or for 18+ only

Thanks for sharing. I was always interested in entering adult games market, since I've got pretty wild imagination and all this stuff is like a second nature to me.What types of games are you guys int...

weixin_35806032的博客 1万+

实现电脑同时上内网和外网(或通过外网访问到该电脑通过该电脑访问内网)

一、需求描述 目前使用的公司网络只能够上内网,但是又有上外网查资料的需求: ①想要实现电脑既能上内网的同时也可以上外网; ②想要使用其他外网电脑使用外网连接到该电脑,通过该电脑访问内部的网络内容。 二、准备内容 电脑必须具备两个网卡,即:可以同时连接内网和外网(比如我的笔记本就可以:使用网线连接笔记本网口与内网通讯,使用WIFI连接手机热点访问外部网络); 注意:如果只有一个网口,可以另外购买USB的无线网卡来实现上网卡。 三、实现电脑同时上内网和外网的操作步骤 3.1、网络拓扑图 ..

提供C#相关开发 、云计算、运维测试、网络安全相关技术分享与服务,有意向可联系。 2万+

利用createImageData新建像素

http://book.51cto.com/art/201304/389322.htm 《HTML5 Canvas游戏开发实战》第2章Canvas基本功能,本章主要讲解HTML5 Canvas的基本功能,利用Canvas的API,展示一些基本图形的绘制及操作方法,包括画线、画图、文字操作及图片操作等。本节为大家介绍利用createImageData新建像素。 AD:

我的地盘 1962

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

【coco2d-html5简单游戏开发】一、连锁反应小游戏

最近在做什么?很多兄弟可能想知道,放着Ideas和Ominds不做,blog也不更新,该有很多人在骂了吧。呵呵,其实,我也很迷茫很纠结,是啊,ideas到底该做成什么样?ominds又该如何,半个月以来一直没有停止过思考,完全没有任何想法,总觉的自己已经没有思想了,快死了吗? 还是做了个简单的东西,首先是我的个人简历(点击查看)  这个就不做过多介绍了,毕竟没有什么技术可言,只不过是一时兴起,也

jov123的专栏 2504

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

cocos2d-javascript试用小记

这几天在整理知易教程的第6个示例,代码基本上完成了,就是文字比较费劲。总觉得有些地方说的很啰嗦,但是意思却表达的不是非常清楚。所以寻思着弄点儿动态的效果到页面上。做GIF动画吧,好像挺麻烦的,还容易失真。用flash吧,好像有些浏览器看不到flash对吧。最近html5好像挺火的,操作canvas什么的要用javascript,从头开始,对于只会点儿基本语法的我,这个难度也不小。 忽然想起来co...

weixin_30740295的博客 303

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

HTML5开发 页游/手游动画及游戏系列教程(Game Tutorial):(一)物体动起来吧

前言 所谓高手,也就是熟悉别人制定的游戏规则、并且能在规则内跳舞的人。(随笔,转自王哲的博客) 09年的时候,为了跳槽和兴趣,转型游戏行业,因此去网上找资料学习各种游戏相关的资料。也是缘分吧,看到了深蓝色右手的教程,当时真是如获至宝,相恨见晚,光看电子书还觉得不够,还把网上的教程都打印了出来,封装成一本书看,这样可以空的时候翻翻。。。。。。。。。。。。。。。。。。。。。。。。。。。

核武器基地的专栏 2万+

HTML5开发 页游/手游动画及游戏系列教程(Game Tutorial):(二)基本动画(canvas先生很忙)

我们这里又一次要请出我们的主角canvas先生 了,canvas先生含有这个drawImage技能,我们的动画就全靠它施展魔法了。 drawImage() 此方法比较复杂,可以有3个、5个或9个参数 3个参数:最基本的 drawImage使用方法。一个参数指定图像位置,另两个参数设置图像在 canvas中的位置。 这里我们使用一下第一个方法,代码如 func

核武器基地的专栏 6943

基于引擎开发HTML5游戏实战(一)---游戏引擎

最近从一个技术沙龙活动中了解到一个游戏引擎(construct2), 这款引擎彻底地改变了游戏开发在我心目中的印象。以前看过一些游戏开发的书籍,基本上都是从canvas,从坐标系讲起,再加上复杂地绘图编程,使得我不 敢对游戏开发有所奢望,更别提那些大制作。但基于这款引擎让我在2个小时之内根据官方tutorial就能搞出一个看上去还不错的web游戏,并且不需要 一行代码,有点当年第一次接触ruby

走向架构师之路 2万+

零代码入门:利用开源HTML5游戏源码打造可销售游戏包全流程

HTML5游戏开发基于HTML、CSS和JavaScript等Web前端技术,其核心原理是利用现代浏览器的Canvas或WebGL渲染能力实现跨平台的互动体验。这项技术的价值在于降低了游戏开发的门槛,使非专业开发者也能快速创建和部署轻量级游戏。在应用场景上,HTML5游戏广泛用于网站互动、营销活动、教育课件及产品原型验证。本文聚焦于一个具体的工程实践:如何合规地寻找、修改、打包开源HTML5游戏源码,并将其作为数字商品进行销售。整个过程无需编写复杂代码,主要涉及素材替换、参数调整和文件管理,是数字产品变现和

weixin_33888907的博客 616

jQuery-黑白反斗棋

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head&gt...

weixin_34018169的博客 188

终极对比指南:为什么选择Leaf游戏服务器框架而非其他方案?

在众多游戏服务器框架中,**Leaf游戏服务器框架**以其卓越的Go语言实现和出色的开发体验脱颖而出。如果你正在寻找一个既高效又易用的游戏服务器解决方案,Leaf框架无疑是你的最佳选择。本文将通过全面对比分析,揭示为什么Leaf游戏服务器框架在众多方案中胜出,帮助你做出明智的技术决策。🚀 ## 🔥 为什么Leaf游戏服务器框架是明智之选? ### 1. 极简设计哲学 Leaf框架遵循"简

gitblog_00676的博客 1169

Tuesday JS游戏上线指南:快速解决CORS跨域报错,用Cordova打包移动端App

**Tuesday JS** 是一款免费、开源、基于网页的视觉小说编辑器,整个游戏只需一个 HTML 页面加 [tuesday.js](https://link.gitcode.com/i/1fb96f5d19825fedd0a5c2a6bb698855) 引擎就能在浏览器中运行。这篇文章将带你完成游戏上线的最后一公里:把构建好的 Tuesday JS 游戏部署到网上、快速解决令人头疼的 CORS

gitblog_00596的博客 458

比qt更好的 跨平台_更好的跨平台开发:Microsoft教程系列的重点

最近,我们一直在运行Microsoft技术传播者赞助的一系列教程,旨在帮助您解决构建在所有平台上都能正常运行的问题。 如果您错过了它,这里是一些亮点。 在iOS,Mac OS X和Android上测试Internet Explorer的快速,准确方法 微软最近推出了一种新工具 ,无论您使用哪种平台,都可以更轻松地在IE中测试网站。 它称为RemoteIE ,旨在提供IE最新版本的虚...

Web design 教程小屋 415

【前端+Canvas+航天】长征十号乙火箭回收全流程动画

中国新型可回收火箭长征十号乙(CZ-10B)海上网系回收动画演示摘要: 该HTML5 Canvas动画完整模拟了长征十号乙火箭从发射到海上回收的7个关键阶段: 发射阶段 - 7台液发100发动机点火,产生890吨推力 上升阶段 - 5米直径箭体垂直爬升 分离阶段 - 63米高火箭在60公里高度完成两级分离 入轨阶段 - 二子级继续将16吨载荷送入轨道 返回阶段 - 一子级完成翻转机动和再入控制 捕获阶段 - 2.5万吨级"领航者号"平台展开绳网系统 收束阶段 - 火箭精准落入网中完成回收 技术特点: 采用真

LIU_CAN的博客 878

H5学习开启誓师文!

最近对H5很感兴趣,想深入研究下。特发文,激励自己~~   free程序猿一只,不是大牛,当不了大腿,但有一颗小强的心!纯属兴趣,开了个公众号(FreePenix_House)以作激励。编程底子是C,C++起家,目前正在做PHP,熟悉SQL,写过java,玩过android,撩过html+css,逗过js,碰过WSDL,认识XML,晓得MVC,涉猎虽广但是精通并不很多。也是该选择出自

freepenix 的学习之路 444
上一篇: 一些文章和各种资源
下一篇: 2011 09 19 日学习总结
程序员迈克
博客等级 码龄16年 36粉丝 71原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值