level solid; basic collision/gravity
parent
66991ce9b8
commit
456ef37653
Binary file not shown.
After Width: | Height: | Size: 7.2 KiB |
@ -0,0 +1,56 @@
|
||||
#ifndef COMPONENTS_SOLID_HPP
|
||||
#define COMPONENTS_SOLID_HPP
|
||||
|
||||
#include "components/point.hpp"
|
||||
#include "window.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
class Solid {
|
||||
public:
|
||||
Solid(const char *path) {
|
||||
bitmap = sdl2LoadSolid(path);
|
||||
}
|
||||
|
||||
~Solid() {
|
||||
if (bitmap != nullptr)
|
||||
SDL_FreeSurface(bitmap);
|
||||
}
|
||||
|
||||
float collision(Vec2 p) const noexcept {
|
||||
float dy = 0.f;
|
||||
|
||||
if (at(p)) {
|
||||
auto up = p;
|
||||
while (up.y > 0 && at(up))
|
||||
up.y--;
|
||||
|
||||
auto down = p;
|
||||
while (down.y < bitmap->h && at(down))
|
||||
down.y++;
|
||||
|
||||
if (down.y - p.y > p.y - up.y)
|
||||
dy = -(p.y - up.y);
|
||||
else
|
||||
dy = down.y - p.y;
|
||||
}
|
||||
|
||||
return dy;
|
||||
}
|
||||
|
||||
private:
|
||||
SDL_Surface *bitmap;
|
||||
|
||||
bool at(Vec2 p) const noexcept {
|
||||
const auto bm = reinterpret_cast<std::uint8_t *>(bitmap->pixels);
|
||||
const int x = std::clamp(static_cast<int>(p.x), 0, bitmap->w);
|
||||
const int y = std::clamp(static_cast<int>(p.y), 0, bitmap->h);
|
||||
const int i = y * bitmap->w + x;
|
||||
const auto val = bm[i * bitmap->format->BytesPerPixel];
|
||||
return val > 0;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // COMPONENTS_SOLID_HPP
|
||||
|
Loading…
Reference in New Issue