首页  >  文章  >  web前端  >  开发日志 - 我正在创建一个游戏引擎!

开发日志 - 我正在创建一个游戏引擎!

PHPz
PHPz原创
2024-09-12 18:15:38288浏览

Devlog - Je créé un moteur de jeu !

我正在创建一个游戏引擎!

这场伟大的冒险简介

几周以来,我一直在定期从事一个我认为可能很有趣的项目,即基于 canvas 使用 JavaScript 和 HTML5 创建我的视频游戏引擎。

您可能想知道为什么选择 HTML5 和 JavaScript 来创建视频游戏?答案没有问题那么酷,是我的学校(Zone01 Normandie)所需的项目的竞争以及这些语言拥有执行该项目所需的一切的事实,促使我选择了这些技术

但实际上这些并不是我会选择作为基础的语言,在完成这个任务后我一定会用不同的语言开始其他类似的冒险。

建筑学

所以我开始设计我的视频游戏引擎,它将由几个类组成,包括至少两个主要类:Game 类将管理整个游戏区域,而 GameObject 类允许您生成对象我们的游戏并让它们互相互动。

对于这些类,我将添加 CollideBox 类,它将允许我管理所有对象的碰撞框。

Game 类有一个 GameLoop 方法,将在游戏的每一帧(图像)执行,还有一个 Draw 方法,将在每个游戏循环期间调用。

对于GameObject类,它有一个Step方法和一个Draw方法。
第一个执行每轮游戏循环,第二个每次调用 GameLoop 类的 Draw 方法时执行。

理论上,您可以通过将引擎模块导入到项目中来创建游戏。
为了显示精灵,我选择使用 HTML5 内置的canva API(内置意味着它默认附带)
它将允许我显示所有精灵并重新剪切图像以创建对我来说非常有用的动画!

几天后,我能够以给定的速度显示动画,并通过我的 CollideBox 检测碰撞。
还有很多其他好东西,我会让你在下面看到:

GameObject 类

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()   {};
}   

游戏类

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
    }
}

当然有很多优化或其他错误,但一切都正常,
“完美的!”你能告诉我吗?
那就太简单了。

忧虑

完成此任务并开始尝试使用此引擎创建游戏后,我在与同事的谈话中得知了一些可怕的消息。

我想您还记得所做的技术选择是为了符合我的 Zone01 学校的要求......
确实,选择的语言很好,但我不知道有一条指令会严重阻碍该项目......
我们被禁止使用 Canva 库!

提醒一下,这是我们用来显示图像的库。

接下来是什么?

当我写这篇文章时,我也开始完全重新设计这个游戏引擎,而不使用canva。

本开发日志已经完成,您很快就会看到这个故事的其余部分,别担心。
对于下一个开发日志,我一定会尝试新的格式。

希望这些内容对您有所帮助,给您带来乐趣,或者至少在一些主题上对您进行了教育。祝您一天愉快,编码愉快。

DevLogs 1.1:引擎完成了,它是如何工作的?

之前

几个月前,我开始创建我的视频游戏引擎,我完成了它......不久前,在 Zone01 的几位同事的帮助下,我们甚至成功地创建了一款受《超级马里奥兄弟》启发的游戏,可以在我的网站上找到Itch.io 页面。

决定申请这个开发日志的格式花了很多时间,我承认我稍微推迟了甚至完全推迟了写这篇文章的截止日期。
通过耐心地以我犹豫不决为借口不从事这个主题,我现在发现自己在计划发布日期两个月后在鲁昂汽车站的休息区写作,而取消的火车迫使我多等一个小时。

따라서 아키텍처의 모든 세부 사항은 무시하겠습니다. 이 아키텍처는 내 개발 블로그의 첫 번째 부분 이후로 거의 변경되지 않았습니다(캔버스 사용을 피하여 적응한 것 제외).
따라서 수행한 프로젝트, 팀으로 일하는 방식 및 직면한 문제에 대해 이야기하겠습니다.
이 글을 이 프로젝트에 대한 피드백으로 삼으시고, 귀하의 프로젝트에 도움이 될 몇 가지 교훈을 이 글에서 얻으실 수 있기를 바랍니다.

프로젝트

이 프로젝트는 최소한 코드 측면에서는 JavaScript로 슈퍼 마리오 브라더스를 다시 만들고 처음부터 시작하는 것이었습니다.

사양은 간단했습니다. 여러 레벨이 있는 마리오 게임이 있어야 했고, 이를 통해 새로운 레벨을 간단하게 만들 수 있었습니다.
또한 옵션을 조정하기 위해 점수판과 메뉴를 만들어야 했습니다.

이 프로젝트의 어려움은 다음과 같습니다.

  • 화면 요소의 수평 스크롤
  • 화면에 없는 요소 최적화

플레이어 위치를 기준으로 모든 요소가 백그라운드에서 스크롤되어야 하기 때문에 스크롤합니다.
그리고 화면에 표시되지 않는 요소들을 최적화하면 성능 저하 없이 게임을 실행하는 데 필요한 리소스를 줄이는 데 도움이 됩니다.

이러한 어려움을 해결한 후 우리는 이 게임을 내 itch.io 페이지에 게시하여 직접 테스트해 볼 수도 있습니다.

이렇게 개발 블로그가 끝났습니다. 이제 끝났으니 다른 프로젝트나 다른 주제에 대해 쓸 수 있겠네요.

내가 말하는 내용에 조금이라도 관심이 있다면 ​​github에서 내 다양한 ​​프로젝트(이 개발 블로그에 포함된 프로젝트 포함)를 확인하실 수 있습니다.

오늘도 좋은 하루 보내세요!

以上是开发日志 - 我正在创建一个游戏引擎!的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn