Permalink
Browse files

sprite size/offset

  • Loading branch information...
ssloy committed Feb 9, 2019
1 parent 323e3f7 commit 3d99cf0bb63a5a95a9868dbc1c1f011ace665c15
Showing with 21 additions and 0 deletions.
  1. +21 −0 tinyraycaster.cpp
@@ -32,6 +32,26 @@ void map_show_sprite(Sprite &sprite, FrameBuffer &fb, Map &map) {
fb.draw_rectangle(sprite.x*rect_w-3, sprite.y*rect_h-3, 6, 6, pack_color(255, 0, 0));
}

void draw_sprite(Sprite &sprite, FrameBuffer &fb, Player &player, Texture &tex_sprites) {
// absolute direction from the player to the sprite (in radians)
float sprite_dir = atan2(sprite.y - player.y, sprite.x - player.x);
while (sprite_dir - player.a > M_PI) sprite_dir -= 2*M_PI; // remove unncesessary periods from the relative direction
while (sprite_dir - player.a < -M_PI) sprite_dir += 2*M_PI;

float sprite_dist = std::sqrt(pow(player.x - sprite.x, 2) + pow(player.y - sprite.y, 2)); // distance from the player to the sprite
size_t sprite_screen_size = std::min(1000, static_cast<int>(fb.h/sprite_dist)); // screen sprite size
int h_offset = (sprite_dir - player.a)/player.fov*(fb.w/2) + (fb.w/2)/2 - tex_sprites.size/2; // do not forget the 3D view takes only a half of the framebuffer
int v_offset = fb.h/2 - sprite_screen_size/2;

for (size_t i=0; i<sprite_screen_size; i++) {
if (h_offset+i<0 || h_offset+i>=fb.w/2) continue;
for (size_t j=0; j<sprite_screen_size; j++) {
if (v_offset+j<0 || v_offset+j>=fb.h) continue;
fb.set_pixel(fb.w/2 + h_offset+i, v_offset+j, pack_color(0,0,0));
}
}
}

void render(FrameBuffer &fb, Map &map, Player &player, std::vector<Sprite> &sprites, Texture &tex_walls, Texture &tex_monst) {
fb.clear(pack_color(255, 255, 255)); // clear the screen

@@ -76,6 +96,7 @@ void render(FrameBuffer &fb, Map &map, Player &player, std::vector<Sprite> &spri

for (size_t i=0; i<sprites.size(); i++) {
map_show_sprite(sprites[i], fb, map);
draw_sprite(sprites[i], fb, player, tex_monst);
}
}

0 comments on commit 3d99cf0

Please sign in to comment.