用 C 語言構(gòu)建網(wǎng)頁游戲
作者:Angus Cheng
圣誕節(jié)快到了啤咽。當(dāng)我過去在銀行工作時奥洼,整個 12 月和 1 月的部分時間,我們都被置于“更改凍結(jié)”狀態(tài)搀擂。在此期間,我們不允許將更新部署到我們的應(yīng)用程序卷玉。我們的想法是:
- 很多人在圣誕節(jié)期間都離開了
- 應(yīng)用程序更改可能會導(dǎo)致崩潰
- 知道如何修復(fù)這些崩潰的人可能已經(jīng)離開了
為了防止這種情況哨颂,他們只是阻止了我們部署更新。這意味著 12 月是在銀行工作的相當(dāng)輕松的時期相种,也是進行大規(guī)模重構(gòu)威恼、清理 TODO 或使用一些新技術(shù)的好時機。那么寝并,學(xué)習(xí)用 C 語言編寫游戲并將其構(gòu)建到 WebAssmebly 怎么樣箫措?
1. 安裝 Raylib
轉(zhuǎn)到此處以在您的操作系統(tǒng)上安裝 Raylib。在 Windows 上衬潦,我使用了在 itch.io 上可用的安裝程序斤蔓,對于 MacOS,我使用了 Homebrew镀岛。
2. 創(chuàng)建 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;
}
創(chuàng)建此文件并將其放在 src/main.c
中
3. 復(fù)制此圖像
[圖片上傳失敗...(image-b1017f-1722583403188)]
復(fù)制此圖像并將其放置在 src/resources/smile.png
4A. 構(gòu)建 MacOS
gcc -Wall -fcolor-diagnostics -fansi-escape-codes -g src/main.c `pkg-config --libs --cflags raylib` -o out/main.out
4B. 構(gòu)建 Windows
gcc src/main.c -lraylib -lopengl32 -lgdi32 -lwinmm -g -o out/main.exe
運行構(gòu)建
# 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)]
如果你做對了弦牡,你應(yīng)該看到這一點。如果沒有漂羊,羞愧地垂下頭驾锰。
5. 下載 Emscripten
現(xiàn)在我們已經(jīng)在 Windows 或 Mac 上成功構(gòu)建了,我們可以準備好構(gòu)建到 Web Assembly走越。我建議您將 emsdk 克隆到您的游戲目錄所在的同一目錄中椭豫。您不必這樣做,但它將使運行我們將要創(chuàng)建的構(gòu)建腳本變得更加容易。
# 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. 創(chuàng)建shell.html
下載此 HTML 文件并將其放在 /shell.html
中赏酥。它將圍繞我們的網(wǎng)絡(luò)組裝游戲進行包裝喳整。
7. 創(chuàng)建構(gòu)建腳本
#!/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
將此文件復(fù)制到 /build-wasm.sh
則必須更改 -I 和 -L 路徑。
如果它有效今缚,瀏覽器應(yīng)該打開并顯示此頁面.
Github 倉庫
所有源文件都可以在這里找到.