current position:Home>JavaScript makes a simple "aircraft war"

JavaScript makes a simple "aircraft war"

2022-05-15 03:07:20AR.K

Old rules , Let's start with the final renderings :

Aircraft battle - Google Chrome 2022-05-09 18-27-36

Next, let's start writing the project case ;
1. Project preparation
Project analysis ,
Basic preparation .
First of all, let's analyze this Project analysis , Insert picture description here
We need to background . The plane . The bullet . Enemy planes flying in and out These four elements
Then all elements appear dynamically , The aircraft can be operated by users .
 Insert picture description here
There is an impact event and a failed pop-up window

Basic preparation
First create a html file , And what it needs img Document and js file .
 Insert picture description here
And in html Call in file js file ( Of course, you can also call while writing )
 Insert picture description here

     All our actions are triggered in the timer 
    function start() {
        timer = setInterval(function() {

Picture query can refer to The author's JavaScript Use built-in objects Mach One way to make a sky full of stars ( Click this title to jump to this article )
How to use it Ali's iconfont Vector library to get the resources we need , Download directly here png Just file it .
Next, let's start writing the formal project :
2. The motion of the background image
Add one div The interface acts as a tab for the project :

<div id="container"></div>

Make some simple style settings for the interface

        #container {
            width: 320px;
            height: 560px;
            background-image: url(img/bg.jpg);
            background-size:  100% 100%;
            position: relative;
            margin: 0 auto;

Conduct js operation :

 Let's get the element first 
    var dContainer = document.getElementById("container");
 Set the width and height of the interface respectively 
    var sw = 320;
    var sh = 560;

We insert the picture as a background image , Here's a point to note position location , After that, the motion of several other elements must be absolutely positioned according to the background image .
Then start writing the background picture js part :
js/bg.js part

var dis = 0;	 The movement of the background image 
var speed = 5;   Movement speed 
function bgMove() {
    dis += 5;   Each move 5
    dis = dis>sh ? 0 : dis;    Ternary operator   When the moving distance of the background image is greater than the height of the interface, it is 0 Otherwise, it will be the original height 
     Pass the width and height to the of the background label css style   Wide for 0  Because you don't need to move left and right , The height needs to move down : = `0 ${

Let's write another public method here , Used to store the methods we need to call
Write a random function here ,( If you want to know, you can see this JavaScript Use built-in objects Mach One way to make a sky full of stars ):
js/public.js part

 Common method 
function rand(min,max) {
    return Math.round(Math.random() * (max-min) +min);

In this js A judgment function is written in the file for media query

 Judge whether it is mobile terminal 
function isPhone() {
        var arr = ["iPhone","iPad","Android"];
        var is = false;
        for(var i=0; i<arr.length; i++){
            if (navigator.userAgent.includes(arr[i])){
                is = true;
        return is;

Corresponding js Add the part of the mobile terminal after the operation :

    var dContainer = document.getElementById("container");
    var sw = 320;
    var sh = 560;
     Added mobile terminal judgment 
        sw = window.innerWidth;
        sh = window.innerHeight;

2. Movement and operation control of aircraft
Let's add a div, For the addition of aircraft

    <div id="container">
        <div id="hero"></div>

be modeled on css:

        #hero {
            width: 66px;
            height: 82px;
            background-image: url(img/hero.png);
            background-size:  100% 100%;
            position: absolute;  Pay attention to the absolute positioning here , Position relative to parent , The next two lines of operation can be performed 
            left: 127px;
            top: 476px;

Next is the mobile operation part of the aircraft js/hero.js

 Get the element first 
var dHero = document.getElementById("hero");
 Add state , Judgment for movement 
var isLeft = false;
var isTop = false;
var isRight = false;
var isBottom = false;
 Press event 
window.onkeydown = function(e) {
    // console.log(e.keyCode);  Here we can get the value of our keyboard keys , You can see... On the console 
    if(e.keyCode === 37){
        isLeft = true;
    }else if(e.keyCode === 38){
        isTop = true;
    }else if(e.keyCode === 39){
        isRight = true;
    }else if(e.keyCode === 40){
        isBottom = true;
 Raise the event 
window.onkeyup = function(e) {
    if(e.keyCode === 37){
        isLeft = false;
    }else if(e.keyCode === 38){
        isTop = false;
    }else if(e.keyCode === 39){
        isRight = false;
    }else if(e.keyCode === 40){
        isBottom = false;

We use Boolean values to judge the State , In the operation of moving, you only need to see flase still true You can move

function heroMove() {
 First get the offset of the aircraft element 
    var left = dHero.offsetLeft;
    var top = dHero.offsetTop;
 Let's make a direct judgment here   Because it is carried out at the same time, we use four peers if sentence 
    if (isLeft) {
        left -= 8;				 The distance of each move 
        left= left<-10 ? -10 : left;   Ternary operator   When the moving distance is greater than the interface, it is 0 Otherwise, it will be the original 
    if (isTop) {
        top -= 8;
        top = top<0 ? 0 : top;
    if (isRight) {
        left += 8;
        left= left>sw-56 ? sw-56 : left;
    if (isBottom) {
        top += 8;
        top = top>sh-82 ? sh-82 : top;
     Finally, assign the obtained value to the style of the aircraft = left + 'px'; = top + 'px';

Next, let's write a mobile operation of the mobile terminal

 Touch screen events 
dHero.ontouchstart = function(e) {
    e.preventDefault();   Eliminate the default action 
    if (e.touches.length > 1){
        return ;
    var touch = e.touches[0];
    var x = touch.pageX;
    var y = touch.pageY;
    var l = dHero.offsetLeft;
    var t = dHero.offsetTop;

    window.ontouchmove = function(e) {
        var touch2 = e.touches[0]; = touch2.pageX - x + l +'px'; = touch2.pageY - y + t +'px';

3. Creation and movement of enemy aircraft
stay html Add div label

 This tag has only storage permission , No operation authority ( Please savor this sentence )
        <div id="enemy">
         Here we will annotate the enemy aircraft , We are js Dynamically create enemy aircraft in 
            <!-- <div class="enemy"></div> --> 

Add corresponding css

        .enemy {
            width: 38px;
            height: 34px;
            background-image: url(img/enemy.png);
            position: absolute;
            background-size: 100% 100%;

Next is js/enemy.js part :

 Get elements 
var dEnemy = document.getElementById("enemy");
 Create enemy aircraft 
function creatEnemy() {
	dom Operation creation div label 
    var enemy = document.createElement('div');
    enemy.className = 'enemy'; = rand(0,sw-38) +'px';  Call random functions ( We've written in public methods before , Call directly here )
    enemy.speed = rand(3,8);
    dEnemy.appendChild(enemy); Store the created enemy aircraft in the parent 
 Here is an extended operation , Because the previous creation will make the number of enemy aircraft appear the same every time ( And the speed of the timer is 30 millisecond   Make the number of enemy aircraft too large )
 We use an operation here 
var diff = 200;

 Define a variable and make the random number in  0~diff  This makes it smaller than  10, So just change diff The value of can make less than 10 The number of has a range ,
diff The bigger it is   Less than 10 The number of occurrences is less likely , On the contrary, it is bigger 

function enemyMove() {
    if (rand(0,diff) <= 10){
      // probability 

    var es = dEnemy.children;   All enemy planes 
    for(var i=0; i<es.length; i++) {
       Traverse all enemy planes 
        var e = es[i];     	    Every enemy plane 
        if(e.offsetTop > sh-40){
       When the position of the enemy aircraft is greater than the interface height, make it disappear 
            dEnemy.removeChild(e);    Delete enemy aircraft   Make it disappear 
            i--;    // Prevent element leakage 
            continue;          Exit this cycle and enter the next cycle 
        } = e.offsetTop + e.speed + 'px';   Update the location of each enemy plane 

4. The creation and movement of bullets
stay html Add div label

   <div id="container">
        <div id="hero"></div>
        <div id="enemy">
            <!-- <div class="enemy"></div> -->
         With the creation of enemy aircraft , Only storage permissions   No administrative rights 
        <div id="bullet">
            <!-- <div class="bullet"></div> -->

The movement of bullets js/bullet.js part :

 Get elements 
var dBullet = document.getElementById("bullet");
 Create bullets 
function creatBullet() {
    var bullet = document.createElement('div');
    bullet.className = 'bullet';
 The bullet appeared from the head of the plane   So the location should get the distance from the plane = dHero.offsetLeft + 33 - 8 + 'px'; = dHero.offsetTop + 'px';
 The movement of bullets 
function bulletMove() {
    var bs = dBullet.children;

 Traverse each bullet 
    for(var i=0; i<bs.length; i++){
        var top = bs[i].offsetTop;
        if(top <= -14){
        bs[i] = top - 20 + 'px';

Actually Writing here, we will find that the operation of bullets and enemy aircraft is almost the same , It's just , The bullet came from one place , The enemy plane appeared in many places
And fill in css part

        .bullet {
            width: 16px;
            height: 20px;
            background-image: url(img/bullet.png);
            position: absolute;
            background-size: 100% 100%;
            top: 476px;;

5. collision detection
This is the most important part , We will fly , The bullet Separate collisions with enemy aircraft Trigger different events
About collision detection We have the following picture
 Insert picture description here
When r2<l1 , b2<t1 ,r1<l2,b1<t2 There will be no collision

function isCrash(a,b) {
    var l1 = a.offsetLeft;
    var t1 = a.offsetTop;
    var r1 = l1 + a.offsetWidth;
    var b1 = t1 + a.offsetHeight;

    var l2 = b.offsetLeft;
    var t2 = b.offsetTop;
    var r2 = l2 + b.offsetWidth;
    var b2 = t2 + b.offsetHeight;
	 collision detection 
    if(r2<l1 || b2<t1 || r1<l2 || b1<t2) {
        return false;
    } else{
        return true;

Next, let's call the collision detection function And trigger the corresponding event

function check() {
    var bs = dBullet.children;   All the bullets 
    var es = dEnemy.children;    All enemy planes 

    for(var i=0; i<es.length; i++){
        Traverse all enemy planes 
        var e = es[i];		  Every enemy plane 
            alert(" Failure ");   Popup 
        // Collision detection of bullets and enemy aircraft 
        for(var j=0; j<bs.length; j++){
            var b = bs[j];
                dBullet.removeChild(b);    Delete the bullet 
                dEnemy.removeChild(e);     Delete the enemy plane 

6, Last , We call all the functions in the timer

    function start() {
        timer = setInterval(function() {

That's the use js Made a simple aircraft war , You can wear one for three times if you like

copyright notice
author[AR.K],Please bring the original link to reprint, thank you.

Random recommended