Sprite shows up every alternate run

in the C++ Fundamentals: Game Programming For Beginners, scarfy shows up on every alternate run; hitting debug run will show blank window, closing and hitting debug again and scarfy shows up. everything else works fine. here is the code:

#include “raylib.h”

#include <stdio.h>

int main() {

// window parameters

const int window_width {800};

const int window_height {600};

int rectVelocity {0};

int gravity {1000};

int JumpVelocity {-600};

bool isInAir {false};

float deltaT {GetFrameTime()};

SetTargetFPS(60);

InitWindow(window_width, window_height, "DASHER");



Texture2D scarfy = LoadTexture("textures/scarfy.png");

if (scarfy.width <= 0 || scarfy.height <= 0) {

printf("*********************Failed to load texture: textures/scarfy.png\n");

return 1; // Exit the program with an error code

}

Rectangle scarfyRec;

scarfyRec.width = scarfy.width / 6;

scarfyRec.height = scarfy.height;

Vector2 scarfyPos;

scarfyPos.x = window_width/2 - scarfyRec.width/2;

scarfyPos.y = window_height - scarfyRec.height;

//DrawTextureRec(scarfy, scarfyRec, scarfyPos, WHITE);

    while (!WindowShouldClose())

{

    deltaT = GetFrameTime();

    BeginDrawing ();

    ClearBackground (WHITE);

   

    if (scarfyPos.y >= (window_height - scarfyRec.height))

    {

        rectVelocity = 0;

        isInAir = false;

    }

    else

    {

        // add gravity

        rectVelocity += gravity * deltaT;

    }

    if (IsKeyPressed(KEY_SPACE) && !isInAir)

    {

        rectVelocity += JumpVelocity;

        isInAir = true;

    }

    // update Y position

    scarfyPos.y += rectVelocity * deltaT;

    DrawTextureRec(scarfy, scarfyRec, scarfyPos, WHITE);

   

    EndDrawing ();

}

UnloadTexture(scarfy);

CloseWindow();

}

Hi Irfan,

It looks like you forgot to set the x and y values of scarfyRec to 0. When your code runs, it doesn’t know which initial values to set so it sets junk data, which would lead to confusing behaviour like what you’ve observed. You just need to add these two lines below setting width and height.

scarfyRec.x = 0;
scarfyRec.y = 0;
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms