在Raylib C++中实现角色/精灵始终朝向鼠标光标可行吗?
在Raylib C++中实现角色朝向鼠标光标
完全可以实现,不需要借助任何额外工具,Raylib内置的向量运算和数学函数就能搞定。核心逻辑是计算角色与鼠标的方向向量,将其转换为旋转角度后应用到精灵上。
实现步骤
- 获取角色(精灵)的中心坐标,以及当前鼠标的屏幕坐标。
- 计算鼠标位置与角色中心的差值向量,以此确定方向。
- 将差值向量转换为弧度角度,再转为Raylib绘图所需的角度值。
- 以精灵中心为旋转原点,绘制带旋转角度的精灵。
完整代码示例
#include "raylib.h" int main() { const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "Sprite Face Mouse"); // 加载你的精灵纹理,替换为实际路径 Texture2D sprite = LoadTexture("character.png"); // 初始位置设为屏幕中心 Vector2 spritePos = { screenWidth / 2.0f, screenHeight / 2.0f }; float spriteRotation = 0.0f; SetTargetFPS(60); while (!WindowShouldClose()) { // 计算朝向逻辑 Vector2 mousePos = GetMousePosition(); // 得到从角色到鼠标的方向向量 Vector2 direction = Vector2Subtract(mousePos, spritePos); // 计算与向上方向的夹角(如果精灵初始朝右,基准向量换成(1,0)) spriteRotation = Vector2Angle((Vector2){0, 1}, direction); BeginDrawing(); ClearBackground(RAYWHITE); // 使用DrawTexturePro实现中心旋转 DrawTexturePro( sprite, (Rectangle){0, 0, sprite.width, sprite.height}, (Rectangle){spritePos.x, spritePos.y, sprite.width, sprite.height}, (Vector2){sprite.width / 2, sprite.height / 2}, // 旋转原点为精灵中心 spriteRotation * RAD2DEG, // 弧度转角度 WHITE ); EndDrawing(); } UnloadTexture(sprite); CloseWindow(); return 0; }
关键注意事项
- 必须使用
DrawTexturePro而非DrawTexture,前者支持自定义旋转原点,确保精灵围绕自身中心旋转,不会出现偏移。 Vector2Angle的基准向量需匹配你的精灵初始朝向:如果精灵默认向上,用(0,1);默认朝右则用(1,0)。- Raylib的旋转参数是角度值,所以需要用
RAD2DEG宏将Vector2Angle返回的弧度转换为角度。
内容的提问来源于stack exchange,提问作者mixalis hadjittofi
相关产品推荐
相关产品推荐

