Home > Web Front-end > H5 Tutorial > Detailed introduction to code examples of html5 mini game production ideas

Detailed introduction to code examples of html5 mini game production ideas

黄舟
Release: 2017-03-20 15:29:43
Original
3467 people have browsed it

html5Detailed explanation of small game production ideas

Introduction

Create canvas

Game loop

Hello world

Create player

Keyboard control

a:Use jQuery Hotkeys

b:Mobile player

Add more game elements

Cannonballs

Enemy

Use Image

Collision Detection

Sound

Introduction

You want to use HTML5Canvas Make a game? Follow this tutorial and you'll be on your way in no time.

Reading this tutorial requires at least familiarity with javascript related knowledge.

You can play the game first or read the article directly and download the game source code.

Create Canvas

Before drawing anything, we must create a canvas. Because this is a complete guide, and we will be using jQuery.

var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;
var canvasElement = $("<canvas width=&#39;" + CANVAS_WIDTH + 
                      "&#39; height=&#39;" + CANVAS_HEIGHT + "&#39;></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo(&#39;body&#39;);
Copy after login

Game Loop

In order to present the player with a coherent and smooth gameAnimation, we have to render the canvas frequently To deceive the player's eyes.

var FPS = 30;
setInterval(function() {
  update();
  draw();
}, 1000/FPS);
Copy after login

Now we don’t care about the implementation of update and draw. The important thing is that we need to know that setInterval() will periodically execute update and draw

Hello world
Copy after login

Now we have set up a loop On the shelf, we modify the update and draw methods to write some text to the screen.

function draw() {
  canvas.fillStyle = "#000"; // Set color to black
  canvas.fillText("Sup Bro!", 50, 50);
}
Copy after login

Expert reminder: Execute the program when you change some code slightly, so that you can find the program error faster.

Still text is displayed normally. Because we already have a loop, we can easily make the text move~~~

var textX = 50;
var textY = 50;
function update() {
  textX += 1;
  textY += 1;
}
function draw() {
  canvas.fillStyle = "#000";
  canvas.fillText("Sup Bro!", textX, textY);
}
Copy after login

Execute the program. If you follow the above step by step, you can see the text move. But the text from the last time is still on the screen because we didn't erase the canvas. Now we add the erase method to the draw method.

function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  canvas.fillStyle = "#000";
  canvas.fillText("Sup Bro!", textX, textY);
}
Copy after login

Now you can see the text moving on the screen, it is a real game, just a half-finished product.

Create player

Create a object that contains all the information of the player, and it must have a draw method. A simple object is created here that contains all player information.

var player = {
  color: "#00A",
  x: 220,
  y: 270,
  width: 32,
  height: 32,
  draw: function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  }
};
Copy after login

We now use a solid color rectangle to represent the player. When we add it to the game, we need to clear the canvas and draw the player.

function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  player.draw();
}
Copy after login

Keyboard Control

Use jQuery Hotkeys

jQuery Hotkeys plugin can be more easily compatible with different browsers when handling keyboard behavior. So that developers don’t have to worry about different keyCode and charCode between different browsers, we bind event like this:

$(document).bind("keydown", "left", function() { ... });
移动player
function update() {
  if (keydown.left) {
    player.x -= 2;
  }
  if (keydown.right) {
    player.x += 2;
  }
}
Copy after login

Does it feel like the movement is not fast enough? So let's increase its movement speed.

function update() {
  if (keydown.left) {
    player.x -= 5;
  }
  if (keydown.right) {
    player.x += 5;
  }
  player.x = player.x.clamp(0, CANVAS_WIDTH - player.width);
}
Copy after login

We can easily add other elements, such as cannonballs:

function update() {
  if (keydown.space) {
    player.shoot();
  }
  if (keydown.left) {
    player.x -= 5;
  }
  if (keydown.right) {
    player.x += 5;
  }
  player.x = player.x.clamp(0, CANVAS_WIDTH - player.width);
}
player.shoot = function() {
  console.log("Pew pew");
  // :) Well at least adding the key binding was easy...
};
Copy after login

Add more game elements

Cannonballs

We start the real game To add a cannonball, first, we need a collection to store it:

var playerBullets = [];
Copy after login

Then, we need a constructor to create the cannonball:

function Bullet(I) {
  I.active = true;
  I.xVelocity = 0;
  I.yVelocity = -I.speed;
  I.width = 3;
  I.height = 3;
  I.color = "#000";
  I.inBounds = function() {
    return I.x >= 0 && I.x <= CANVAS_WIDTH &&
      I.y >= 0 && I.y <= CANVAS_HEIGHT;
  };
  I.draw = function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  };
  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;
    I.active = I.active && I.inBounds();
  };
  return I;
}
Copy after login

When the player fires, we need to fire into the collection Add shells:

player.shoot = function() {
  var bulletPosition = this.midpoint();
  playerBullets.push(Bullet({
    speed: 5,
    x: bulletPosition.x,
    y: bulletPosition.y
  }));
};
player.midpoint = function() {
  return {
    x: this.x + this.width/2,
    y: this.y + this.height/2
  };
};
Copy after login

Modify the update and draw methods to implement firing:

function update() {
  ...
  playerBullets.forEach(function(bullet) {
    bullet.update();
  });
  playerBullets = playerBullets.filter(function(bullet) {
    return bullet.active;
  });
}
function draw() {
  ...
  playerBullets.forEach(function(bullet) {
    bullet.draw();
  });
}
Copy after login
enemy
enemies = [];
function Enemy(I) {
  I = I || {};
  I.active = true;
  I.age = Math.floor(Math.random() * 128);
  I.color = "#A2B";
  I.x = CANVAS_WIDTH / 4 + Math.random() * CANVAS_WIDTH / 2;
  I.y = 0;
  I.xVelocity = 0
  I.yVelocity = 2;
  I.width = 32;
  I.height = 32;
  I.inBounds = function() {
    return I.x >= 0 && I.x <= CANVAS_WIDTH &&
      I.y >= 0 && I.y <= CANVAS_HEIGHT;
  };
  I.draw = function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  };
  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;
    I.xVelocity = 3 * Math.sin(I.age * Math.PI / 64);
    I.age++;
    I.active = I.active && I.inBounds();
  };
  return I;
};
function update() {
  ...
  enemies.forEach(function(enemy) {
    enemy.update();
  });
  enemies = enemies.filter(function(enemy) {
    return enemy.active;
  });
  if(Math.random() < 0.1) {
    enemies.push(Enemy());
  }
};
function draw() {
  ...
  enemies.forEach(function(enemy) {
    enemy.draw();
  });
}
Copy after login

Use Picture

player.sprite = Sprite("player");
player.draw = function() {
  this.sprite.draw(canvas, this.x, this.y);
};
function Enemy(I) {
  ...
  I.sprite = Sprite("enemy");
  I.draw = function() {
    this.sprite.draw(canvas, this.x, this.y);
  };
  ...
}
Copy after login

Collision detection

function collides(a, b) {
  return a.x < b.x + b.width &&
         a.x + a.width > b.x &&
         a.y < b.y + b.height &&
         a.y + a.height > b.y;
}
function handleCollisions() {
  playerBullets.forEach(function(bullet) {
    enemies.forEach(function(enemy) {
      if (collides(bullet, enemy)) {
        enemy.explode();
        bullet.active = false;
      }
    });
  });
  enemies.forEach(function(enemy) {
    if (collides(enemy, player)) {
      enemy.explode();
      player.explode();
    }
  });
}
function update() {
  ...
  handleCollisions();
}
function Enemy(I) {
  ...
  I.explode = function() {
    this.active = false;
    // Extra Credit: Add an explosion graphic
  };
  return I;
};
player.explode = function() {
  this.active = false;
  // Extra Credit: Add an explosion graphic and then end the game
};
Copy after login

Add sound

function Enemy(I) {
  ...
  I.explode = function() {
    this.active = false;
    // Extra Credit: Add an explosion graphic
  };
  return I;
};
player.explode = function() {
  this.active = false;
  // Extra Credit: Add an explosion graphic and then end the game
};
Copy after login

The above is the detailed content of Detailed introduction to code examples of html5 mini game production ideas. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template