I am not sure what I am doing wrong here
Main:
#include “raylib.h”
#include “raymath.h”
#include “Character.h”
int main()
{
const int windowWidth{384};
const int windowHeight{384};
InitWindow(windowWidth, windowHeight, "Classy Clash");
Texture2D map = LoadTexture("nature_tileset/OpenWorldMap24x24.png");
Vector2 mapPos{0.0, 0.0};
const float mapScale{4.0f};
Character knight{windowWidth, windowHeight};
SetTargetFPS(60);
while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(WHITE);
mapPos = Vector2Scale(knight.getWorldPos(), -1.f);
DrawTextureEx(map, mapPos, 0.0, mapScale, WHITE);
knight.tick(GetFrameTime());
if (knight.getWorldPos().x < 0.f ||
knight.getWorldPos().y < 0.f ||
knight.getWorldPos().x + windowWidth > map.width * mapScale - 50 ||
knight.getWorldPos().y + windowHeight > map.height * mapScale - 50)
{
knight.undoMovement();
}
EndDrawing();
}
CloseWindow();
}
Character.h:
#include “raylib.h”
class Character
{
public:
Character(int winWidth, int winHeight);
Vector2 getWorldPos() { return worldPos; }
void tick(float deltaTime);
void undoMovement();
private:
Texture2D texture{LoadTexture("characters/knight_idle_spritesheet.png")};
Texture2D Idle{LoadTexture("characters/knight_idle_spritesheet.png")};
Texture2D Run{LoadTexture("characters/knight_run_spritesheet.png")};
Vector2 screenPos{};
Vector2 worldPos{};
Vector2 worldPosOld{};
float rightLeft{1.f};
float runningTime{};
int frame{};
int maxFrames{6};
float updateTime{1.f / 12.f};
float speed{4.f};
float width{};
float height{};
float scale{4.0f};
};
character.cpp:
#include “Character.h”
#include “raymath.h”
Character::Character(int winWidth, int winHeight)
{
width = texture.width / maxFrames;
height = texture.height;
screenPos = {static_cast<float>(winWidth) / 2.0f - scale (0.5f * width),
static_cast<float>(winHeight) / 2.0f - scale (0.5f * height)
};
}
void Character::tick(float deltaTime)
{
worldPosOld = worldPos;
Vector2 direction{};
if (IsKeyDown(KEY_A))
direction.x -= 1.0;
if (IsKeyDown(KEY_D))
direction.x += 1.0;
if (IsKeyDown(KEY_W))
direction.y -= 1.0;
if (IsKeyDown(KEY_S))
direction.y += 1.0;
if (Vector2Length(direction) != 0.0)
{
worldPos = Vector2Add(worldPos, Vector2Scale(Vector2Normalize(direction), speed));
direction.x < 0.f ? rightLeft = -1.f : rightLeft = 1.f;
texture = Run;
}
else
{
texture = Idle;
}
runningTime += deltaTime;
if (runningTime >= updateTime)
{
frame++;
runningTime = 0.f;
if (frame > maxFrames)
frame = 0;
}
Rectangle source{frame * width, 0.f, rightLeft * width, height};
Rectangle dest{screenPos.x, screenPos.y, scale * width, scale * height};
DrawTexturePro(texture, source, dest, Vector2(), 0.f, WHITE);
}
void Character::undoMovement()
{
worldPos = worldPosOld;
}