javascript - 将 requirejs 用于模块化游戏引擎

标签 javascript requirejs game-engine

我是一名经验丰富的 JavaScript 程序员,我正在尝试从头开始编写自己的模块化游戏引擎。我以前没有使用过 requirejs,但在阅读了一些相关内容之后,听起来它可能是管理引擎所有组件并将它们加载到一个连贯结构中的最佳方式。

我的主要问题是我不太确定如何真正使用 requirejs。我一直在查看他们的 API 文档,但我不确定如何将其与我布置项目的方式相集成。

目前,我的项目使用以下结构:

  • src
    • engine.js //This contains the common engine stuff, most notably the engine namespace
    • resource
      • resource-module.js //This is the module constructor, which handles all the common stuff between the different substructures
      • sprites.js //This is a substructure that contains sprite loading code
    • render
    • etc...
    • third-party
      • jquery
      • requirejs

我希望能够独立加载模块。例如,应该可以从引擎中移除音频模块,它仍然可以工作。替换模块或添加新模块也应该很容易。

此外,我正在使用 jQuery 进行事件处理,因此需要在引擎启动之前加载它。

您可以在这里找到我当前的来源:https://github.com/superlinkx/lithium-engine

我知道当前的代码很乱,还没有完全构建,但我大部分时间仍在弄清楚如何最好地构建它。任何帮助/建议将不胜感激,但我主要关心的是如何使用 requirejs 构建它,以便更容易编译成单个文件以供生产使用。

最佳答案

Require.js 不强制你的文件的任何特定结构。您可以在 require 配置中指定完整路径,或者只在 require() 或 define() 调用中使用完整路径。两者都可以,但是后者可以节省您的输入时间,并且当您包含来自许多不同位置的内容时,可以更轻松地移动内容:

var $ = require("third-party/jquery");

require.config({
    paths: {
        "jquery": "third-party/jquery"
    }
});
var $ = require("jquery");

I want to be able to load the modules independently of each other. It should be possible for instance to remove the audio module from the engine, and it still work. It should also be easy to substitute modules, or add new modules.

这不是 require.js 做的四件事。您可以决定何时以及何时不加载它,但您必须确保它不会破坏您的其余代码。

Also, I'm using jQuery for event handling, so it needs to be loaded before the engine is initiated.

您可以通过几种不同的方式做到这一点。

  • 在您的 main.js 中要求()它以便始终加载它(您也可以使用包含 jQuery 的 require-jquery.js)。
  • 将 jQuery 指定为引擎的依赖项

require.config({
    paths: {
        "jquery": "path.to.jquery",
        "engine": "path.to.engine"
    },
    shim: {
        "engine": {
            "deps": ["jquery"]
        }
    }
});
  • 将 jQuery 传递给模块中的 define() 调用(可能是最佳选择)

define(["jquery"], function ($) {
    // your engine code
}

关于javascript - 将 requirejs 用于模块化游戏引擎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15967294/

相关文章:

javascript - 如何在 Laravel 的 cookie 中的表单步骤之间存储 Vue 状态?

javascript - 结合 AngularJS、RequireJS 和 asp.NET 时出错

javascript - Requirejs 和 karma : cannot detect the source file

JavaScript roundslider 插件默认设置

javascript - 为什么我在 IE 中收到此 "null or not an object"错误?

javascript - 带有回调函数的异步 API 请求

javascript - 无法通过 gulp 在我的 karma runner Mocha 测试中使用 require

game-engine - Godot - set_fixed_process 函数

JavaFX 对话 - 游戏

Javafx 图像无法正确渲染