Aircraft shooting game based on HTML

Procedural ape without hair loss 2020-11-13 05:33:59
aircraft shooting game based html


Catalog

1、 Game design ideas

2、 Aircraft shooting game design steps


This blog will share an article based on HTML Simple airplane shooting game , Below is the player's plane , You can press the space bar to continuously fire bullets , Above are random enemy aircraft . Players can control the movement of their own aircraft through the keyboard key , When the bullets of the player's plane hit the enemy plane , Enemy aircraft explodes . The running effect of the game is shown in the figure below :

1、 Game design ideas

1、 Game material

Enemy planes are used in the game 、 Our plane 、 The bullet 、 Pictures of the explosion of the enemy plane being hit , Use them as shown in the figure below :

2、 The principle of map scrolling is realized  

A simple example , Everyone has been on the train , I've met my own train when I'm on the train. It's obviously stopped , But the train on the next track is going backwards , There is an illusion that your train is moving forward . The map principle of the flying shooting game is exactly the same as this one . The player is controlling where the plane flies on the screen , The background image scrolls back and forth, giving the player the illusion that the plane under his control is flying forward .

As shown in the figure below, the map image scrolls alternately at the back of the screen , This will give players the illusion that the plane they control is moving forward .

Map scrolling related code , As shown below : 

function updateBg() {
/** Update the game background image to achieve the effect of scrolling down **/
mBitposY0 += 5;// The first map map_0.png The vertical coordinates of the 5 Pixel
mBitposY1 += 5;// The second map map_1.png The vertical coordinates of the 5 Pixel
if (mBitposY0 == mScreenHeight) { // Beyond the bottom of the game screen
mBitposY0 = -mScreenHeight;// Back to the top of the screen
}
if (mBitposY1 == mScreenHeight) {// Beyond the bottom of the game screen
mBitposY1 = -mScreenHeight; // Back to the top of the screen
}
}

3、 The realization of airplanes and bullets

The airplane used in the game 、 Bullets are implemented with corresponding classes . Because there will be a lot of bullets , There will also be a lot of enemy aircraft , So each bullet needs to use an object to record the current bullet in the screen X,Y coordinate . Every enemy plane is also an object , It's also recorded on the screen X,Y coordinate . In this way, the collision result can be calculated by traversing the bullet object and the enemy aircraft object when dealing with the collision , So we can get the collision object and play the death explosion animation .

Every time during the game 3 Seconds to add an enemy plane , Players press the space bar to fire bullets and initialize their position coordinates in front of the player's plane . Constantly update the position of the game background picture in regular events , Move down 5 Pixel , To achieve the effect of scrolling down , At the same time, the position of each bullet is updated every time 1 Pixel , Update enemy position ( Every time 1 Pixel ), Finally, detect the collision between the bullet and the enemy plane .

In this way, when dealing with collision, it is actually the collision between the rectangular area of each bullet and the rectangular area of each enemy plane . By traversing the bullet object and the enemy aircraft object, the collision result can be calculated , So we can get the collision object and play the death explosion animation .

2、 Aircraft shooting game design steps

1、 Design bullets

Create a Bullet class , Used to indicate a bullet , Update bullet coordinates , Draw bullet animation and move up 1 Pixel . The bullet has 4 The frame of , Every time 10 Time interval ( Each interval is 1000/60=16.67 millisecond ) Change the frame . The code is as follows :

// Bullets
var Bullet = function (image, x, y) {
this.image = image;
this.x = x;
this.y = y;
this.width = image.width/4;
this.height = image.height ;
this.frm = 0; // What frame is it
this.dis = 0; // How much time interval
};

Detection point (x, y) Whether it's in the bullet zone ( This game does not use ), The code is as follows :

Bullet.prototype.testPoint = function (x, y) {
var betweenX = (x >= this.x) && (x <= this.x + this.width);
var betweenY = (y >= this.y) && (y <= this.y + this.height);
return betweenX && betweenY;
};

move Change the position of the bullet , The code is as follows :

Bullet.prototype.move = function (dx, dy) {
this.x += dx;
this.y += dy;
};

 draw Draw bullet animation and move up 1 Pixel . Every time 10 One frame at a time , The bullets are 4 frame ( chart 14-7 Shown ). Bullet coordinates update main changes y coordinate ( vertical direction ) value , Every time 1 Pixel . Of course, it can also be modified x coordinate ( horizontal direction ) value , There's no change here for simplicity x Coordinate value ( horizontal direction ), The code is as follows :

Bullet.prototype.draw = function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height,
0, 0, this.width, this.height);// Draw bullet correspondence this.frm frame
ctx.restore();
this.y--; // Move upward 1 Pixel
this.dis++;
if (this.dis >= 10) {//10 One frame at a time
this.dis = 0;
this.frm++;
if (this.frm >= 4) this.frm = 0;
}
}; 

hitTestObject Whether the bullet collided with the plane , The code is as follows :

 Bullet.prototype.hitTestObject = function (planobj) {
if(isColliding(this.x,this.y,this.width,this.height,
planobj.x,planobj.y,planobj.width,planobj.height))// Collide
return true;
else
return false;
}

isColliding The global function is the second collision detection method in the previous analysis , The code is as follows :

function isColliding( ax, ay, aw, ah, bx, by, bw, bh)
{
if(ay > by + bh || by > ay + ah
|| ax > bx + bw || bx > ax + aw)
return false;
else
return true;
}

2、 Designing airplanes

Create one in the project Plan class , Used to denote enemy and friendly aircraft , Realize aircraft coordinate update , Drawing function . It functions like bullets .

In the constructor image It's a picture of the plane ,(x, y) It's the plane's position coordinates , And the last parameter n It's this plane. It's a few frames of animation , For example, your plane is 6 Frame animation , The enemy plane is 2 Frame animation , The effect is as follows :

Player planes and enemy planes

The implementation code is as follows :

var Plan = function (image, x, y, n) {
this.image = image;
this.x = x;
this.y = y;
this.originX = x;
this.originY = y;
this.width = image.width / n; // The width of the plane per frame
this.height = image.height; // The altitude of each frame
this.frm = 0;
this.dis = 0;
this.n = n;
};
Plan.prototype.testPoint = function (x, y) {
var betweenX = (x >= this.x) && (x <= this.x + this.width);
var betweenY = (y >= this.y) && (y <= this.y + this.height);
return betweenX && betweenY;
};
Plan.prototype.move = function (dx, dy) {
this.x += dx;
this.y += dy;
};
Plan.prototype.Y = function ( ) {
return this.y;
};

draw (ctx) Moving down the plane , At the same time, there is displacement in the horizontal direction , Using sinusoidal motion , The implementation code is as follows :

Plan.prototype.draw = function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height,
0, 0, this.width, this.height);
ctx.restore();
this.y++; // Move down 1 Pixel
this.x = this.originX + 20 * Math.sin(Math.PI / 100 * this.y);// Horizontal sinusoidal movement
this.dis++;
if (this.dis >= 3) {//3 Change the graph at intervals
this.dis = 0;
this.frm++;
if (this.frm >= this.n) this.frm = 0;
}
};

draw2 (ctx) The plane is not animated in place , Because your plane is manually controlled to move , So we need this function , The implementation code is as follows :

Plan.prototype.draw2 = function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height,
0, 0, this.width, this.height);
ctx.restore();
this.dis++;
if (this.dis >= 3) {//3 Change the graph at intervals
this.dis = 0;
this.frm++;
if (this.frm >= this.n) this.frm = 0;
}
};
// Collision detection between aircraft
// If it overlaps, it means the plane is in collision .
Plan.prototype.hitTestObject = function (planobj) {
if(isColliding(this.x,this.y,this.width,this.height,
planobj.x,planobj.y,planobj.width,planobj.height)) // Collide
return true;
else
return false;
}

3、 Explosion

Explosion animation is called simple , Just draw the explosion in place 6 Frame can be , The effect is as follows :

The enemy plane exploded 6 Frame image

The implementation code is as follows :

// Explosion animation
var Bomb= function (image, x, y) {
this.image = image;
this.x = x;
this.y = y;
this.width = image.width/6;
this.height = image.height ;
this.frm = 0;
this.dis = 0;
};
Bomb.prototype.draw2 = function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
if (this.frm >= 6) return ;//6 The frame drawing is over
ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height,
0, 0, this.width, this.height);
ctx.restore();
this.dis++;
if (this.dis >= 10) {//10 Change the graph at intervals
this.dis = 0;
this.frm++;
}
};

 4、 Design the main program

Used to implement the game background interface , Load game related images , Complete the shot 、 Enemy aircraft moving , Collision detection and other functions , The implementation code is as follows :

 var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
document.addEventListener("keydown", onkeydown);
var plans = []; // Array of enemy objects
var bullets = []; // Array of bullet objects
var bombs = []; // Explosion object array
var score=0;
var overflag = false; // Is the game over ,true For the end
var mBitposY0, mBitposY1;
/** The width and height of the screen * */
var mScreenWidth = 320;
var mScreenHeight = 480
var myplane;// Your plane
var image = new Image();
var image2 = new Image();
var image3 = new Image();
var image4 = new Image();
var image5 = new Image();
// Here are two pictures of the game background
var background0 = new Image();
background0.src = "map_0.png";
var background1 = new Image();
background1.src = "map_1.png";

init() Initialize the initial position of the two pictures of the game background ,updateBg() Through these two background pictures moving down and switching, the dynamic moving effect of game background is realized , The implementation code is as follows :

function init() {
/** Game background * */
/** The first picture is subsidized on the screen (0,0) spot , The second picture is above the first one * */
mBitposY0 = 0;
mBitposY1 = -mScreenHeight;
}
function updateBg() {
/** Update the game background image to achieve the effect of scrolling down **/
mBitposY0 += 5;
mBitposY1 += 5;
if (mBitposY0 == mScreenHeight) {
mBitposY0 = -mScreenHeight;
}
if (mBitposY1 == mScreenHeight) {
mBitposY1 = -mScreenHeight;
}
}
image.src = "plan.png";// Pictures of my own plane
image.onload = function () {
};
image2.src = "bomb.png";// Explosion pictures
image2.onload = function () {
};
image3.src = "enemy.png";// Pictures of enemy aircraft 

After the image is loaded successfully , By timing every 3 Seconds produce 1 Enemy aircraft , Constantly update the background image position in another timer , Draw our own plane and enemy plane , And check whether the enemy plane touches the player's own plane ( Then the game is over ) Or the bullet hits the enemy plane , Finally, draw the explosion object , Implement game logic .

If the bullet hits an enemy plane , Then the object of explosion , From the enemy plane array plans Delete the enemy aircraft in the , From the bullet array bullets Delete the colliding bullet in . If you miss the enemy plane , And then determine if the bullet is flying out of the top of the screen , Fly out of the top of the screen from the array bullets Delete the colliding bullet in . The implementation code is as follows :

image3.onload = function () {
myplane = new Plan(image, 300 * Math.random(), 400, 6); //6 Picture size
init(); // Initialize background map location
plan_interval = setInterval(function () {
plans.push(new Plan(image3, 300 * Math.random(), 20 * Math.random(), 2)); //2 Picture size
}, 3000); //3 Seconds produce 1 Enemy aircraft
setInterval(function () {
context.clearRect(0, 0, 320, 480);
// Draw a map
//context.drawImage(background, 0, 0);
context.drawImage(background0, 0, mBitposY0);
context.drawImage(background1, 0, mBitposY1);
updateBg();// Update background image location
// Draw your own plane
if (!overflag)// The game is not over
myplane.draw2(context); // Stay where you are
// Drawing enemy planes
for (var i = plans.length - 1; i >= 0; i--) {
if (plans[i].Y() > 400) // The enemy plane flies to the bottom and disappears
plans.splice(i, 1); // Delete enemy aircraft
else
plans[i].draw(context);
}
// Draw bullets
for (var i = bullets.length - 1; i >= 0; i--) {
if (bullets[i].Y() < 0)
bullets.splice(i, 1); // Delete the bullet
else
bullets[i].draw(context);
}
// collision detection
// Judge that the enemy plane encounters the player's own plane
for (var i = plans.length - 1; i >= 0; i--) {
e1 = plans[i];
if (e1 != null && myplane != null && myplane.hitTestObject(e1)) {
clearInterval(plan_interval); // Clear timer , No more enemy aircraft
plans.splice(i, 1); // Delete enemy aircraft
bombs.push(new Bomb(image2, myplane.x, myplane.y));
//bomb_interval=setInterval(function () {
// bomb.draw2(context);// Stay where you are
//}, 1000 / 60);
message_txt.innerHTML = " The enemy plane encounters the player's own plane , Game over ";
overflag = true;
}
}
// Judge that the bullet hit the enemy plane
for (var j = bullets.length - 1; j >= 0; j--) {
var b1 = bullets[j];
for (var i = plans.length - 1; i >= 0; i--) {
e1 = plans[i];
if (e1 != null && b1 != null && b1.hitTestObject(e1))// Hit the enemy plane
{
plans.splice(i, 1); // Delete enemy aircraft
bullets.splice(i, 1); // Delete this bullet
bombs.push(new Bomb(image2, b1.x, b1.y - 36));
message_txt.innerHTML = " The enemy plane was hit , Add 20 branch ";
score += 20;
score_txt.innerHTML = " fraction :" + score + " branch ";
}
}
}
// Painting explosion
for (var i = bombs.length - 1; i >= 0; i--) {
if (bombs[i].frm >= 6)
bombs.splice(i, 1); // Delete the explosion
else
bombs[i].draw2(context);
}
}, 1000 / 60);
};
image4.src = "bullet.png";// Bullet picture
image4.onload = function () {
};

The user buttons control the plane to move up and down, left and right , And space to fire bullets .onkeydown(e) Respond to the user's keystrokes , Modify the coordinates of the player's own plane , As shown below :

function onkeydown(e) {
if (e.keyCode==32) {// Space
// bullets
bullets.push(new Bullet(image4, myplane.x, myplane.y-36));//
}else if (e.keyCode==37) {// towards the left
myplane.move(-10,0);
}else if (e.keyCode==39) {// towards the right
myplane.move(10,0);
}else if (e.keyCode==38) {// Up
myplane.move(0,-10);
}else if (e.keyCode==40) {// Down
myplane.move(0,10);
}
}

5、 The game page

The implementation code is as follows :

<!DOCTYPE html>
<html>
<head>
<title> Aircraft battle 2017</title>
<meta charset="utf-8">
</head>
<body>
<canvas id="myCanvas" width="320" height="480" style="border:solid">
Your browser does not support it canvas Canvas elements , Please update the browser to get the demo effect .
</canvas>
<div id="message_txt" style="display:block;"> Aircraft battle </div>
<div id="score_txt" style="display:block;"> fraction :0 branch </div>
</body>
</html>

Project arrangement comes from : Tsinghua computer school

Project source download : Pay attention to WeChat public number , Reply key : Airplane shooting game , Get project resources ~

版权声明
本文为[Procedural ape without hair loss]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple