Home Web Front-end H5 Tutorial Code sharing for HTML5 first-person shooter game implementation

Code sharing for HTML5 first-person shooter game implementation

Mar 24, 2017 pm 03:37 PM

Function description:

In the game, while avoiding enemy attacks, you need to collect three different keys, open the corresponding door, and finally reach the destination.

This game is also based on the self-developed HTML5GameFrameworkcnGameJS.

It is recommended to use Chrome browser to view.

Effect preview:

The arrow keys control movement, the space bar shoots, and the shift key opens the door.

 Code sharing for HTML5 first-person shooter game implementationCode sharing for HTML5 first-person shooter game implementation

Implementation analysis:

In the previous article In "HTML5 Realizing 3D Maze", the effect of the 3D scene is simulated through the radiation method, and this article adds more game elements based on the 3D effect to build a more complete first-person shooting game.

How to simulate the 3D scene effect has been described in detail above. This article mainly introduces how to realize the interactive part of the game.

 1. What is the correspondence between the game elements on the map and the objects on the screen?

First of all, each game element corresponds to two game objects. One game object is the object on the left map, and the other is the object on the right screen. For example, information such as the location of an enemy, whether to shoot, status, etc. are all represented by the map object on the left, and the display of the enemy on the screen is drawn based on the information of the object on the map on the left. In short, the map object on the left is responsible for determining the position and status of game elements. It actually stores game information. The screen object on the right is only responsible for the presentation of game elements.

        newEnemy.relatedObj= enemy2({src:srcObj.enemy,context:screenContext});
        newEnemy.relatedObj.relatedParent=newEnemy;
Copy after login
As above, the objects on the map and the objects on the screen maintain a

reference

relationship, so that the screen object can be easily accessed through the map object and vice versa.  

 2. How to make the enemy shoot after discovering the player?

To implement this function, we need to know the angle of the player relative to the enemy. We can find this parameter based on the distance from the enemy to the player and the difference between their x and y. Then we can emit a ray in that direction from the location of the enemy object. If the ray can touch the player without touching the wall, it proves that the enemy can see the player. At this point the enemy can shoot at the player.

nextX = enemyCenter[0];
            nextY = enemyCenter[1];
            while (this.map.getPosValue(nextX, nextY) == 0) {
                distant += 1;
                x = nextX;
                y = nextY;
                if (cnGame.collision.col_Point_Rect(x, y, playerRect)&&!spriteList[i].relatedObj.isCurrentAnimation("enemyDie")) {
                //如果地图上敌人能看到玩家,则向玩家射击
                    spriteList[i].isShooting = true;
                    if (spriteList[i].lastShootTime > spriteList[i].shootDuration) {//检查是否超过射击时间间隔,超过则射击玩家            
                        spriteList[i].shoot(player);
                        spriteList[i].relatedObj.setCurrentImage(srcObj.enemy1);        
                        spriteList[i].lastShootTime = 0;

                    }
                    else {
                        if (spriteList[i].lastShootTime > 0.1) {
                            spriteList[i].relatedObj.setCurrentImage(srcObj.enemy);
                        }
                        spriteList[i].lastShootTime += duration;
                    }
                    break;
                }
                else {
                    spriteList[i].isShooting = false;
                }
                nextX = distant * Math.cos(angle) + enemyCenter[0];
                nextY = enemyCenter[1] - distant * Math.sin(angle);
            }

        }
Copy after login

 

3. How to detect whether the key is obtained?

Detecting key acquisition is actually to simply detect whether the player object and the key object collide. If a collision occurs, the key will be obtained. Collision detection also occurs on the map object on the left.

/*  检测是否获得钥匙    */
var checkGetKeys = function() {
    var list = cnGame.spriteList;
    var playerRect= this.player.getRect();
    for (var i = 0, len = list.length; i < len; i++) {
        if (list[i] instanceof key) {
            if (cnGame.collision.col_Between_Rects(list[i].getRect(),playerRect)) {
                this.keysValue.push(list[i].keyValue);
                list.remove(list[i]);
                i--;
                len--;
            }
        }
    }

}
Copy after login

4. How to draw game elements and game scenes on the screen at the same time and maintain the correct sequence?

In css, we can use

z-Index

to maintain the correct hierarchical relationship of elements, but now we need to draw graphics on canvas, so Only the z-Index effect can be simulated. As mentioned in the previous article, the 3D scene is drawn by pixel lines of different lengths. Therefore, after adding other game elements, if you want to maintain the correct hierarchical relationship, you need to Customize the zIndex attribute for each element and pixel line and store it in an array.

Every time the array is drawn, the array is sorted according to zIndex, so that there is a sequential order for drawing, thereby ensuring the correct level

. The value of zIndex is calculated based on the distance between the player and the element or pixel line:

zIndex= Math.floor(1 / distant * 10000)
Copy after login
After that, each drawing can produce the effect of the near image covering the far image:

Sorting:

colImgsArray.sort(function(obj1, obj2) {

            if (obj1.zIndex > obj2.zIndex) {
                return 1;
            }
            else if (obj1.zIndex < obj2.zIndex) {
                return -1;
            }
            else {
                return 0;
            }
        });
Copy after login

Drawing:

//画出每条像素线和游戏元素
        for (var i = 0, len = colImgsArray.length; i < len; i++) {
            var obj = colImgsArray[i];
            if(obj.draw){
                obj.draw();
            }
            else{
                context.drawImage(obj.img, obj.oriX, obj.oriY, obj.oriWidth, obj.oriHeight, obj.x, obj.y, obj.width, obj.height);
            }
        }
Copy after login

 

5. How to determine when the player hits the enemy?

The judgment of the player hitting the enemy actually uses collision detection, but this time the collision detection is performed using the element on the screen.

We only need to detect whether the rectangle formed by the crosshair (middle point of the screen) collides with the enemy object, and then we can detect whether the enemy is hit.

for (var i = list2.length - 1; i >= 0; i--) {
        if (list2[i] instanceof enemy2 && list2[i].relatedParent.isShooting) {
            var obj = list2[i];
            var enemyRect = obj.getRect();//构造敌人在屏幕上形成的矩形对象
            if (cnGame.collision.col_Point_Rect(starPos[0], starPos[1], enemyRect)) {
                obj.setCurrentAnimation("enemyDie");    
                break;
            }
        }
    }
Copy after login
After hitting the enemy, you need to break out of the loop and stop detection to prevent hitting the enemy behind the enemy.

The above is the detailed content of Code sharing for HTML5 first-person shooter game implementation. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles