Search code examples
cvectorpixelpoint

Drawing pixels which connect 2 points


I'm trying to draw the direction of my player on a minimap. I have the ending point of where to draw and the starting point. I'd like to connect the two to actually draw the direction the player is facing. I have found the ending point using the player direction X and Y. I'm working with pixels.

I'm only allowed to use my school's library for drawing into a window.

Here's how I get the endpoint and starting point (x and y being the player's coordinate (int), dir_x and dir_y are doubles for the direction (double), start.x and y are (ints)).
start.x = x * MAP_ELEM_PX_SIZE + MAP_PLAYER_PX_SIZE / 2 + (MAP_PLAYER_PX_SIZE + 5) * pos.dir_x;
start.y = y * MAP_ELEM_PX_SIZE + MAP_PLAYER_PX_SIZE / 2 + (MAP_PLAYER_PX_SIZE + 5) * pos.dir_y;
end.x = x * MAP_ELEM_PX_SIZE + MAP_PLAYER_PX_SIZE / 2;
end.y = y * MAP_ELEM_PX_SIZE + MAP_PLAYER_PX_SIZE / 2;

I first tried by just iterating over the x and y at the same time like in this method

int     draw_dir_ray(t_coord start, t_coord end, t_win *win)
{
    int i;
    int j;

    i = 0;
    j = 0;
    if (start.x < end.x)
        i = 1;
    else if (start.x > end.x)
        i = -1;
    if (start.y < end.y)
        j = 1;
    else if (start.y > end.y)
        j = -1;
    while (start.x != end.x || start.y != end.y)
    {
        set_pixel(win, start.x, start.y, 0x009E00);
        if (start.x != end.x)
            start.x += i;
        if (start.y != end.y)
            start.y += j;
    }
    return (1);
}

Here are a few screenshots of what it's rendering. As you can see it's not really the expected result... (Though I tried to give the most informations I can provide some more if needed) 1st screenshot 2nd screenshot 3rd screenshot


Solution

  • Thanks to you guys I searched at the Bresenham's line algorithm and implemented it this way !

    int     draw_dir_ray(t_coord start, t_coord end, t_win *win)
    {
        int dx;
        int dy;
        int sx;
        int sy;
        int err;
        int e2;
    
        dx = abs(end.x - start.x);
        dy = -abs(end.y - start.y);
        sx = start.x < end.x ? 1 : -1;
        sy = start.y < end.y ? 1 : -1;
        err = dx + dy;
        while (1)
        {
            set_pixel(win, start.x, start.y, 0xFF0000);
            set_pixel(win, start.x - 1, start.y, 0xFF0000);
            set_pixel(win, start.x, start.y - 1, 0xFF0000);
            set_pixel(win, start.x - 1, start.y - 1, 0xFF0000);
            if (start.y == end.y && start.x == end.x)
                break ;
            e2 = 2 * err;
            if (e2 >= dy)
            {
                err += dy;
                start.x += sx;
            }
            if (e2 <= dx)
            {
                err += dx;
                start.y += sy;
            }
        }
        return (1);