Raylib中RayCollision的Vector3 Normal与Point是什么?附碰撞示例需求
解决Raylib中类Flappy Bird游戏的管道与小鸟碰撞检测问题
在类Flappy Bird游戏中使用Raylib的RayCollision结构体实现管道与小鸟碰撞检测时,若出现小鸟自碰撞,大概率是误将小鸟自身碰撞体纳入检测范围,或射线发射源设置不当。以下是两种可行的实现方案:
方案1:直接使用Raylib内置2D碰撞函数(推荐)
Flappy Bird是2D游戏,Raylib提供了更适配的2D碰撞检测接口,无需手动处理RayCollision的细节,也能避免自碰撞:
// 定义小鸟碰撞体(圆形,更贴合小鸟形状) typedef struct Circle { float x, y; float radius; } Circle; Circle birdCollider = { birdPos.x, birdPos.y, 15.0f }; // 假设小鸟半径为15 // 定义上下管道的矩形碰撞体 Rectangle topPipe = { pipeX, 0, 60, pipeTopHeight }; // pipeX为管道X坐标,60为管道宽度 Rectangle bottomPipe = { pipeX, screenHeight - pipeBottomHeight, 60, pipeBottomHeight }; // 检测碰撞 bool hitTopPipe = CheckCollisionCircleRec(birdCollider, topPipe); bool hitBottomPipe = CheckCollisionCircleRec(birdCollider, bottomPipe); if (hitTopPipe || hitBottomPipe) { // 触发碰撞逻辑,比如游戏结束 // GameOver(); }
方案2:使用RayCollision结构体实现射线检测
若坚持使用RayCollision,需确保射线仅检测管道碰撞体,避免检测到小鸟自身:
// 小鸟中心作为射线起点(Z轴设为0适配2D场景) Vector3 rayOrigin = { birdPos.x, birdPos.y, 0.0f }; // 定义四个方向的射线,检测是否碰撞上下管道 Ray rayRight = { rayOrigin, (Vector3){1.0f, 0.0f, 0.0f} }; RayCollision colRightTop = GetRayCollisionRectangle(rayRight, topPipe); RayCollision colRightBottom = GetRayCollisionRectangle(rayRight, bottomPipe); Ray rayLeft = { rayOrigin, (Vector3){-1.0f, 0.0f, 0.0f} }; RayCollision colLeftTop = GetRayCollisionRectangle(rayLeft, topPipe); RayCollision colLeftBottom = GetRayCollisionRectangle(rayLeft, bottomPipe); Ray rayUp = { rayOrigin, (Vector3){0.0f, -1.0f, 0.0f} }; RayCollision colUp = GetRayCollisionRectangle(rayUp, topPipe); Ray rayDown = { rayOrigin, (Vector3){0.0f, 1.0f, 0.0f} }; RayCollision colDown = GetRayCollisionRectangle(rayDown, bottomPipe); // 判断是否碰撞管道 bool isCollided = colRightTop.hit || colRightBottom.hit || colLeftTop.hit || colLeftBottom.hit || colUp.hit || colDown.hit; if (isCollided) { // 碰撞逻辑 // GameOver(); }
避免自碰撞的关键
- 检测时仅传入小鸟和管道的碰撞体,不要将小鸟自身碰撞体作为检测目标。
- 使用射线检测时,确保射线方向指向管道,且起点不要深入小鸟碰撞体内部(可将起点偏移小鸟半径距离)。
内容的提问来源于stack exchange,提问作者1NEGROUP
相关产品推荐
相关产品推荐

