Page 1 of 1

Checking pixels on a line

Posted: Tue Sep 09, 2014 7:54 pm
by fmra
I'm working on a pathfinding routine and am trying to do something similar to raycasting to to have an agent look ahead to the goal and see if it is clear or obstructed. I've successfully been using a matched imagedata to check for object collision using img:getPixel. I'm wondering if there is a way to ":getPixel" along a line (without drawing the line) to get the color data for each point along the line.

Re: Checking pixels on a line

Posted: Tue Sep 09, 2014 10:24 pm
by davisdude
If it's a straight line, you can do something like this:

Code: Select all

function getLine( x1, y1, x2, y2 ) -- Get two points that you know are on the line- your start and end points. 
    -- ( x1, y1 ) should always be the start.
    -- y = mx + b
    local m = ( y1 - y2 ) / ( x1 - x2 )
    local b = y1 - m * x1
    
    local function sign( x )
        return ( x > 0 and 1 ) or ( x < 0 and -1 ) or 0
    end

    local addx = sign( x1 - x2 )
    for x = x1, x2, addx do
        local y = m * x + b
        -- Put code here. Use 'y' and 'x' as the values.
    end
end
Warning: code is untested.

Re: Checking pixels on a line

Posted: Wed Sep 10, 2014 7:16 am
by Plu
Keep in mind that using getPixel constantly is probably (a lot) slower than pulling the whole image into a lua-table and accessing that.

Re: Checking pixels on a line

Posted: Wed Sep 10, 2014 9:57 am
by zorg
Plu wrote:Keep in mind that using getPixel constantly is probably (a lot) slower than pulling the whole image into a lua-table and accessing that.
On the other hand, tables have some overhead in memory, while imagedata is (to my knowledge) just a simple c array holding byte quadruplets for the pixel colors; so that should consume less memory as a tradeoff... if i am right :3

Re: Checking pixels on a line

Posted: Wed Sep 10, 2014 3:06 pm
by Robin
In general, yes, but LuaJIT can make space optimizations like that (or better) when you use Lua tables, without any extra effort. And recent LÖVE builds are linked to LuaJIT by default, so...