环境安装
这VS code
老是cmake
报错,用于项目开发好像挺麻烦,毕竟只是编译器。
改成用Clion
,VS code
我不太会用于项目开发😩
必要的环境:
- Visual Studio Code
- MSYS2
- MinGW-w64
- raylib
之前安装过MinGW-w64,所以直接安装raylib即可。
安装raylib
进入MSYS2 MINGW64
,使用pacman -S mingw-w64-x86_64-raylib
安装raylib。
创建项目
在你想要的地方创建一个文件夹(我的是 D:\raylib1
),然后用 Clion
打开。
在 Clion
中,右键点击 CMakeLists.txt
文件,选择 Edit CMakeLists.txt
,然后添加以下内容:
1 2 3 4 5 6 7 8 9 10 11 12
| cmake_minimum_required(VERSION 3.16) project(raylib1)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_PREFIX_PATH "C:/msys64/mingw64")
find_package(raylib REQUIRED)
add_executable(raylib1 main.cpp)
target_link_libraries(raylib1 PRIVATE raylib opengl32 gdi32 winmm)
|
如果可以,建议把 Clion
的编译器位置换为你的MinGW-w64的编译器位置,因为之前在 MSYS2 MINGW64
安装过 raylib
库,我不知道用 Clion
自带的能不能找到这个库。
Hello World
接下来,在main.cpp
中输入以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include "raylib.h"
int main() { InitWindow(800, 600, "Hello from CLion + raylib!"); SetTargetFPS(60);
while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(RAYWHITE); DrawText("Hello from raylib + CLion!", 200, 300, 20, DARKBLUE); EndDrawing(); }
CloseWindow(); return 0; }
|
然后点击右上角🔨编译并运行程序,就可以看到窗口中显示 “Hello from raylib + CLion!” 的文字了。
基本操作
以下是我的以一个测试程序,在窗口中显示一个红色方块,并可以通过方向键移动方块,点击鼠标左键在鼠标位置生成蓝色圆点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include "raylib.h" #include <stdio.h> #include <unistd.h>
int main() { char cwd[1024]; #if defined(_WIN32) _getcwd(cwd, sizeof(cwd)); #else getcwd(cwd, sizeof(cwd)); #endif printf("Current working dir: %s\n", cwd);
InitWindow(800, 600, "raylib 中文字体演示"); InitAudioDevice(); SetTargetFPS(90);
int startChar = 0x4E00; int endChar = 0x9FA5; int charsCount = endChar - startChar + 1;
int* chars = (int*)MemAlloc(charsCount * sizeof(int)); for (int i = 0; i < charsCount; i++) { chars[i] = startChar + i; }
Font font = LoadFontEx("assets/XiaolaiSC-Regular.ttf", 24, chars, charsCount); MemFree(chars);
if (font.glyphCount == 0) { printf("字体加载失败!请确认assets文件夹和字体文件是否存在。\n"); font = GetFontDefault(); }
Vector2 textPos = { 10, 10 }; Vector2 boxPos = { 100, 100 }; Vector2 circles[100]; int circleCount = 0;
while (!WindowShouldClose()) {
if (IsKeyDown(KEY_RIGHT)) boxPos.x += 4; if (IsKeyDown(KEY_LEFT)) boxPos.x -= 4; if (IsKeyDown(KEY_DOWN)) boxPos.y += 4; if (IsKeyDown(KEY_UP)) boxPos.y -= 4; if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && circleCount < 100) { circles[circleCount++] = GetMousePosition(); }
BeginDrawing(); ClearBackground(RAYWHITE);
DrawTextEx(font, "raylib 中文字体演示(按方向键移动红色方块)", textPos, 20, 1, DARKBLUE); DrawTextEx(font, "点击鼠标左键在鼠标位置生成蓝色圆点", (Vector2){10, 40}, 18, 1, DARKGRAY);
DrawFPS(700, 10);
DrawRectangleV(boxPos, (Vector2){ 50, 50 }, RED);
for (int i = 0; i < circleCount; i++) { DrawCircleV(circles[i], 10, BLUE); }
EndDrawing(); }
UnloadFont(font);
CloseAudioDevice(); CloseWindow();
return 0; }
|