Home Web Front-end JS Tutorial Devlog - I'm creating a game engine!

Devlog - I'm creating a game engine!

Sep 12, 2024 pm 06:15 PM

Devlog - Je créé un moteur de jeu !

I'm creating a game engine!

Introduction to this great adventure

For a few weeks now I have been working regularly on a project that I think might be interesting to talk about, the creation of my video game engine in JavaScript and HTML5 based on canvas.

You are probably wondering why you chose HTML5 and JavaScript to create video games? The answer is less cool than the question, it is the competition of projects necessary for my school (Zone01 Normandie) and the fact that the languages ​​have everything necessary to carry out this project that led me to choose these technologies.

But actually these are not the languages ​​that I would have chosen as a base and I will surely embark on other adventures of this type with different languages ​​after the finalization of this one.

Architecture

So I got to work designing my video game engine, it will be made up of several classes including at least two main ones: The Game class which will manage the entire game area and the GameObject class allows you to generate the objects in our games and make them interact with each other.

To these classes I will add the CollideBox class which will allow me to manage the collision boxes of all objects.

The Game class has a GameLoop method which will be executed at each frame(image) of the game, a Draw method which will be called during each game loop.

As for the GameObject class, it has a Step method, and a Draw method.
The first executes each round of the game loop and the second each time the Draw method of the GameLoop class is called.

This allows you to theoretically create games by importing the Engine module into a project.
For displaying the sprites I chose to use the canva API which is built-in to HTML5 (built-in means it comes with it by default)
It will allow me to display all the sprites and recut the images in order to create animations which will be extremely useful to me!

After several days I am able to display animations, at a given speed, and detect collisions via my CollideBoxes.
And lots of other nice things that I'll let you see below:

The GameObject class

class GameObject{
    constructor(game) { // Initialize the GameObject
        this.x = 0
        this.y = 0 
        this.sprite_img = {file: undefined, col: 1, row: 1, fw: 1, fh: 1, step: 0, anim_speed: 0, scale: 1}
        this.loaded = false
        this.game = game
        this.kill = false
        this.collision = new CollideBox()

        game.gObjects.push(this)

    };
    setSprite(img_path, row=1, col=1, speed=12, scale=1) {
        var img = new Image();
        img.onload = () => {
            console.log("image loaded")
            this.sprite_img = {file: img, col: col, row: row, fw: img.width / col, fh: img.height / row, step: 0, anim_speed: speed, scale: scale}
            this.onSpriteLoaded()
        };
        img.src = img_path


    }
    onSpriteLoaded() {}
    draw(context, frame) { // Draw function of game object
        if (this.sprite_img.file != undefined) {


            let column = this.sprite_img.step % this.sprite_img.col;
            let row = Math.floor(this.sprite_img.step / this.sprite_img.col);

           // context.clearRect(this.x, this.y, this.sprite_img.fw, this.sprite_img.fh);
            context.drawImage(
                this.sprite_img.file,
                this.sprite_img.fw * column,
                this.sprite_img.fh * row,
                this.sprite_img.fw,
                this.sprite_img.fh,
                this.x,
                this.y,
                this.sprite_img.fw * this.sprite_img.scale,
                this.sprite_img.fh * this.sprite_img.scale
            );

            if (frame % Math.floor(60 / this.sprite_img.anim_speed) === 0) {
                // Mise à jour de step seulement à 12 fps
                if (this.sprite_img.step < this.sprite_img.row * this.sprite_img.col - 1) {
                    this.sprite_img.step += 1;
                } else {
                    this.sprite_img.step = 0;
                }
            }
        }
    }
    distance_to(pos) {
        return Math.sqrt((pos.x - this.x) ** 2 + (pos.y - this.y) ** 2)
    }

    collide_with(box) {
        if (box instanceof GameObject) {
            box = box.collision
        }
        return (
            this.collision.x < box.x + box.w &&
            this.collision.x + this.collision.w > box.x &&
            this.collision.y < box.y + box.h &&
            this.collision.y + this.collision.h > box.y
          )
    }
    onStep()   {};
}   
Copy after login

The Game class

class Game {
    constructor(width = 1400, height = 700) {
        this.gObjects = [];
        this.toLoad = [];
        this.timers = [];
        this.layers = [];
        this.canvas = document.getElementsByTagName("canvas")[0]

        this.canvas.width = width
        this.canvas.height = height
        this.context =  this.canvas.getContext("2d")
        this.context.globalCompositeOperation = 'source-over';
        this.inputs = {};
        this.mouse = {x: 0, y: 0}
        document.addEventListener('keydown', (e) => {
            this.inputs[e.key] = true;
        }, false);
        document.addEventListener('keyup', (e) => {
            this.inputs[e.key] = false;
        }, false);
        document.addEventListener('mousemove', (e) => {
            this.mouse.x = e.x;
            this.mouse.y = e.y;
        })
        document.addEventListener('mouseevent', (e) => {
            switch (e.button) {

            }
        })

    }
    draw(frame) {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        console.log( this.canvas.width, this.canvas.heigh)
        for(let i = 0; i < this.gObjects.length; i ++) {
            this.gObjects[i].draw(this.context, frame)
        }

    }
    gLoop() {
        let fps = Math.floor(1000 / 60)
        console.log(fps)
        let clock = 0
        setInterval(() => {
            clock += 1
            for(let i = 0; i < this.gObjects.length; i ++) {

                if (this.gObjects[i] != undefined) {
                    if (this.gObjects[i].kill) {
                        this.gObjects.splice(i, 1);
                        continue;
                    }
                    this.gObjects[i].onStep();
                }


            }
            this.draw(Math.floor(clock))
               // context.l();

           //     console.log(clock)

           if (fps <= clock) {
            clock = 0
           } 

        }, fps)
    }
    keyboard_check(key) {
        return this.inputs[key] == true
    }
}
Copy after login

There are certainly a lot of optimization or other errors but everything is functional,
"Perfect!" will you tell me?
That would be way too simple.

The worries

After finishing this and starting to test the waters for creating a game with this engine, I learned some terrible news during a conversation with a colleague.

I imagine that you remember that the technology choices made were made to correspond to the requirements of my Zone01 school…
Well indeed the languages ​​chosen were good but I was not aware of an instruction which will very seriously handicap the project…
We were prohibited from using the Canva library!

As a reminder, this is the library that we use to display our images.

What’s next?

As I write this text I am also starting to completely redesign this game engine, without the use of canva.

This devlog is finished and you will have the rest of this story soon, don't worry.
For the next devlog I will definitely try a new format.

Hoping that this content has helped you, entertained you or at least educated you on a few subjects. I wish you a good end of the day and good coding.

DevLogs 1.1: The engine is finished, how does it work?

Previously

A few months ago I started creating my video game engine, I finished it... Quite a while ago, and with the help of several colleagues from Zone01 we even succeeded to create a game inspired by Super Mario Bros available on my Itch.io page.

Deciding the format to apply for this devlog took a lot of time, and I admit I delayed slightly or even completely pushed back the deadline for writing this one.
By patiently taking the excuse of my indecision for not working on this subject, I now find myself two months after the planned release date writing in the rest area of ​​the Rouen bus station while my canceled train forces me to wait an extra hour.

So let's ignore all the details of the architecture, this one having changed very little (apart from the adaptation by avoiding the use of canvases) since the first part of my devlog.
We will therefore talk about the project carried out, the way we worked as a team and the problems we encountered.
See this as feedback on this project, and I hope that you will be able to draw some lessons from this writing that will help you on one of your projects.

The project

The project was to recreate a Super Mario Bros in JavaScript and starting from scratch, at least in terms of the code.

The specifications were simple, we had to have a Mario game with several levels, a way to simply create new ones.
Also we had to create a scoreboard and a menu to adjust the options.

The difficulties of this project were:

  • Horizontal scrolling of elements on the screen
  • Optimization of elements not present on the screen

Scrolling because it requires all elements to scroll in the background relative to the player's position.
And optimizing elements that are not displayed on the screen reduces the resources needed to run the game without loss of performance.

After resolving these difficulties we published this game on my itch.io page where you can even go and test it.

This is how this devlog ends, now finished I will be able to write about other projects and/or other subjects.

If you're even a little interested in what I'm telling you, you can go see my different projects (including those in this devlog) on ​​github.

Have a nice rest of the day!

The above is the detailed content of Devlog - I'm creating a game engine!. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles