Skip to content

Commit

Permalink
sprite size/offset
Browse files Browse the repository at this point in the history
  • Loading branch information
ssloy committed Feb 10, 2019
1 parent 323e3f7 commit 3d99cf0
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions tinyraycaster.cpp
Expand Up @@ -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

This comment has been minimized.

Copy link
@benc-uk

benc-uk Mar 20, 2022

I'd love a little more explanation on this part

This comment has been minimized.

Copy link
@rjkilpatrick

rjkilpatrick Oct 28, 2022

sprite_dir is an angle in radians -Ο€ < sprite_dir ≀ Ο€ (from the definition of atan2), but player.a has no constraints on it (it could be 4Ο€, for example), meaning sprite_dir - player.a produces values outside of (-Ο€,Ο€], so we remove 2Ο€, so that when in line 43, where we divide by the fov, i.e., (sprite_dir - player.a)/player.fov will produce a value between -1 and 1.
Equivalently, we could write ((sprite_dir - player.a) % (2*M_PI))/player.fov to replace the action of the two while loops

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

Expand Down Expand Up @@ -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);
}
}

Expand Down

0 comments on commit 3d99cf0

Please sign in to comment.