i am new to raylib and wanted to make a little 2d ball thing, and i don't know how to stop the sprite from going of the screen, it only works with 2 edges and not the others, would anybody please help?
My C file: game.cpp:
#include <raylib.h>
int main() {
InitWindow(800, 600, "My Game!");
// Vector2 ballPosition = {400.0f, 300.0f};
Vector2 ballPosition = { (float)800/2, (float)600/2 };
SetTargetFPS(60);
while(!WindowShouldClose()) {
if (IsKeyDown(KEY_RIGHT)) ballPosition.x = 2.0f;
if (IsKeyDown(KEY_LEFT)) ballPosition.x -= 2.0f;
if (IsKeyDown(KEY_UP)) ballPosition.y -= 2.0f;
if (IsKeyDown(KEY_DOWN)) ballPosition.y = 2.0f;
DrawText("move the ball with arrow keys", 10, 10, 20, DARKGRAY);
Texture2D ball = LoadTexture("ball.png");
DrawTexture(ball, ballPosition.x - 50, ballPosition.y - 50, WHITE);
if (ballPosition.x < 0) ballPosition.x = 0;
if (ballPosition.x > 800) ballPosition.x = 800;
if (ballPosition.y < 0) ballPosition.y = 0;
if (ballPosition.y > 600) ballPosition.y = 600;
BeginDrawing();
ClearBackground(RAYWHITE);
// Vector2 mousePosition = GetMousePosition();
// ballPosition = mousePosition;
// DrawCircleV(ballPosition, 20.0f, BLUE);
EndDrawing();
}
CloseWindow();
return 0;
}
CodePudding user response:
Took me a while but your problem is a combination of the offset for drawing the ball texture and how you check for the bounds of the screen (assuming the image is a 50x50, you didn't specify).
Notice I've locally added a circle directly at the ballposition (right after the DrawTextureCall):
DrawCircleV(ballPosition, 2.0f, MAROON);
Since this is to the right and bottom of the image, your bounds check will only be correct for the right and bottom edges. For the left and top edges the entire image disappears before the ballposition hits the edge.
In my opinion you should draw the image at the ballposition and adjust the bounds check to take the image size into account:
const float ballHalfSize = ball.width / 2.0f; // assuming square image
DrawTexture(ball, int(ballPosition.x - ballHalfSize), int(ballPosition.y - ballHalfSize), WHITE);
if ((ballPosition.x - ballHalfSize) < 0) ballPosition.x = ballHalfSize;
if ((ballPosition.x ballHalfSize) > 800) ballPosition.x = 800 - ballHalfSize;
if ((ballPosition.y - ballHalfSize) < 0) ballPosition.y = ballHalfSize;
if ((ballPosition.y ballHalfSize) > 600) ballPosition.y = 600 - ballHalfSize;
With this new version I get correct collision behavior on all 4 edges of the screen.