🎹 1. 键盘输入示例(最常用)

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
#include "raylib.h"

int main(void)
{
InitWindow(800, 450, "raylib input example");
SetTargetFPS(60);

while (!WindowShouldClose())
{
// --- 输入处理 ---
if (IsKeyPressed(KEY_SPACE)) {
TraceLog(LOG_INFO, "Space pressed!");
}

if (IsKeyDown(KEY_RIGHT)) {
TraceLog(LOG_INFO, "Holding RIGHT");
}

if (IsKeyReleased(KEY_A)) {
TraceLog(LOG_INFO, "A released");
}

if (IsKeyPressed(KEY_ESCAPE)) {
break; // 退出
}

BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Press SPACE, A, or RIGHT", 200, 200, 20, DARKGRAY);
EndDrawing();
}

CloseWindow();
return 0;
}

常用键盘函数

  • IsKeyPressed(key):按下瞬间触发一次
  • IsKeyDown(key):按住时每帧触发
  • IsKeyReleased(key):松开瞬间触发一次
  • IsKeyUp(key):当前未按下

🖱 2. 鼠标输入示例

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
#include "raylib.h"

int main(void)
{
InitWindow(800, 450, "mouse input example");
SetTargetFPS(60);

while (!WindowShouldClose())
{
Vector2 mouse = GetMousePosition();

if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) {
TraceLog(LOG_INFO, "Left click at (%.0f, %.0f)", mouse.x, mouse.y);
}

if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) {
TraceLog(LOG_INFO, "Holding right button");
}

float wheel = GetMouseWheelMove();
if (wheel != 0) {
TraceLog(LOG_INFO, "Mouse wheel: %.1f", wheel);
}

BeginDrawing();
ClearBackground(RAYWHITE);
DrawCircleV(mouse, 10, RED);
DrawText("Move mouse or click", 10, 10, 20, DARKGRAY);
EndDrawing();
}

CloseWindow();
return 0;
}

常用鼠标函数

  • GetMousePosition()
  • IsMouseButtonPressed(button)
  • IsMouseButtonDown(button)
  • GetMouseWheelMove()

🎮 3. 手柄输入示例(可选)

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
#include "raylib.h"

int main(void)
{
InitWindow(800, 450, "gamepad input example");
SetTargetFPS(60);

while (!WindowShouldClose())
{
if (IsGamepadAvailable(0)) {
if (IsGamepadButtonPressed(0, GAMEPAD_BUTTON_RIGHT_FACE_DOWN)) {
TraceLog(LOG_INFO, "Gamepad A pressed");
}

float lx = GetGamepadAxisMovement(0, GAMEPAD_AXIS_LEFT_X);
float ly = GetGamepadAxisMovement(0, GAMEPAD_AXIS_LEFT_Y);

BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Gamepad connected!", 10, 10, 20, DARKGRAY);
DrawText(TextFormat("Left Stick: %.2f %.2f", lx, ly), 10, 40, 20, DARKGRAY);
EndDrawing();
}
else {
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Connect a gamepad", 10, 10, 20, DARKGRAY);
EndDrawing();
}
}

CloseWindow();
return 0;
}