【问题标题】:Player doesn't move when colliding with the floor玩家与地板碰撞时不会移动
【发布时间】:2021-02-12 12:25:58
【问题描述】:

我正在使用 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 变量。

【问题讨论】:

    标签: c collision-detection raylib


    【解决方案1】:

    因为如果你在地板上,你会不断地与地板发生碰撞。然后位置不会更新。

    我是这么想的:

    pl.newPos.y += G;

    是个问题,因为我认为G 应该加速你,而不是移动你,但显然玩家并没有真正的速度,只是一个位置。目前,您的播放器只能进行 5 步侧身、5 步向上和 3 步向下。好像你一跳就不能着地,因为你会停留在 2 高。

    也许你应该在检查碰撞时分别处理你的 x 和 y 方向(以解决你原来的问题)。您的最小步长似乎也很大,但这取决于游戏的其余部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2018-12-31
      • 2016-03-30
      • 1970-01-01
      相关资源
      最近更新 更多