用 C 语言构建网页游戏
作者:Angus Cheng
圣诞节快到了。当我过去在银行工作时,整个 12 月和 1 月的部分时间,我们都被置于“更改冻结”状态。在此期间,我们不允许将更新部署到我们的应用程序。我们的想法是:
- 很多人在圣诞节期间都离开了
- 应用程序更改可能会导致崩溃
- 知道如何修复这些崩溃的人可能已经离开了
为了防止这种情况,他们只是阻止了我们部署更新。这意味着 12 月是在银行工作的相当轻松的时期,也是进行大规模重构、清理 TODO 或使用一些新技术的好时机。那么,学习用 C 语言编写游戏并将其构建到 WebAssmebly 怎么样?
1. 安装 Raylib
转到此处以在您的操作系统上安装 Raylib。在 Windows 上,我使用了在 itch.io 上可用的安装程序,对于 MacOS,我使用了 Homebrew。
2. 创建 main.c
#include "raylib.h"
int main(void) {
InitWindow(512, 512, "Raylib WASM Example");
Texture2D texture = LoadTexture("resources/smile.png");
while (!WindowShouldClose()) {
BeginDrawing();
ClearBackground(BLACK);
DrawTexture(texture, 0, 0, WHITE);
EndDrawing();
}
UnloadTexture(texture);
CloseWindow();
return 0;
}
创建此文件并将其放在 src/main.c
中
3. 复制此图像
[图片上传失败...(image-b1017f-1722583403188)]
复制此图像并将其放置在 src/resources/smile.png
4A. 构建 MacOS
gcc -Wall -fcolor-diagnostics -fansi-escape-codes -g src/main.c `pkg-config --libs --cflags raylib` -o out/main.out
4B. 构建 Windows
gcc src/main.c -lraylib -lopengl32 -lgdi32 -lwinmm -g -o out/main.exe
运行构建
# Need to run from the src folder because the code wants the resources folder to be in the current working directory.
cd src
# MacOS
../out/main.out
# Windows
../out/main.exe
[图片上传失败...(image-d29178-1722583403188)]
如果你做对了,你应该看到这一点。如果没有,羞愧地垂下头。
5. 下载 Emscripten
现在我们已经在 Windows 或 Mac 上成功构建了,我们可以准备好构建到 Web Assembly。我建议您将 emsdk 克隆到您的游戏目录所在的同一目录中。您不必这样做,但它将使运行我们将要创建的构建脚本变得更加容易。
# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git
# Enter that directory
cd emsdk
# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull
# Download and install the latest SDK tools.
./emsdk install latest
# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest
# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh
6. 创建shell.html
下载此 HTML 文件并将其放在 /shell.html
中。它将围绕我们的网络组装游戏进行包装。
7. 创建构建脚本
#!/bin/bash
set -euo pipefail
# Get EMSDK on the PATH
cd ../emsdk
source emsdk_env.sh
# Get into the /src folder
cd ../raylib-wasm-example
cd src
# Build to Web Assembly
emcc -o ../out/index.html \
main.c -Os -Wall /Users/anguscheng/workspace/raylib/src/libraylib.a \
-I. -I /usr/local/Cellar/raylib/4.5.0/include \
-L. -L /Users/anguscheng/workspace/raylib/src \
-s USE_GLFW=3 \
-s ASYNCIFY \
--shell-file ../shell.html \
--preload-file resources \
-s TOTAL_STACK=64MB \
-s INITIAL_MEMORY=128MB \
-s ASSERTIONS \
-DPLATFORM_WEB
# Get into /out
cd ../out
# Run the game
emrun index.html
将此文件复制到 /build-wasm.sh
则必须更改 -I 和 -L 路径。
如果它有效,浏览器应该打开并显示此页面.
Github 仓库
所有源文件都可以在这里找到.