我正在用 raylib 制作游戏。碰撞似乎有效,但当我接触地面时无法移动。
//including raylib
#include<raylib.h>
//defining the G - gravity
#define G 3.0f
//main function
int main()
{
// player struct
//SetExitKey();
struct player
{
// old position used for colision
Vector2 oldPos;
//new position used for colision
Vector2 newPos;
// simply the player color
Color color;
};
//constants
const int screenWidth=800;
const int screenHeight=450;
float plSpeed=5.0f;
//objects
struct player pl;
pl.newPos.x=screenWidth/2;
pl.newPos.y=screenHeight/2;
pl.color=MAROON;
//player rectangle for colision
Rectangle plr;
//the obsacle
Rectangle floor={
0,400,screenWidth,55,
};
//creating the window
InitWindow(screenWidth,screenHeight,"Raylib Tutorial P1");
//target fps
SetTargetFPS(60);
//Main Game Loop
//heart of the game
while(!WindowShouldClose())
{
// update position
if (IsKeyDown(KEY_RIGHT)) pl.newPos.x += plSpeed;
if (IsKeyDown(KEY_LEFT)) pl.newPos.x -= plSpeed;
if (IsKeyDown(KEY_UP)) pl.newPos.y -= plSpeed;
pl.newPos.y += G;
//colision detection
int coliding=0;
if (CheckCollisionRecs(plr,floor))
{
coliding=1;
}
if(!coliding) pl.oldPos=pl.newPos;
else pl.newPos=pl.oldPos;
//set player rect
plr.x=pl.newPos.x;
plr.y=pl.newPos.y;
plr.width=30;
plr.height=30;
//drawing
BeginDrawing();
//set background color
ClearBackground(RAYWHITE);
DrawRectangleRec(floor,GREEN);
//draw player
DrawRectangleRec(plr,pl.color);
EndDrawing();
}
// De-initialization
CloseWindow();
return 0;
}
在这里我移动玩家,如果他们发生碰撞,我会将他们传送回最后一点。如果不是,我更新oldPos
变量。