Applying texture to mesh?

I’m having trouble applying a texture to a bunch of poly’s. I’m drawing a mesh with the same size as my tex img, and then I try to apply the texture like so:

    m = mesh()
    verts = {}
    for i=1, 4 do
        local pt = vec2(WIDTH/2+100, HEIGHT/2+i*25)
        table.insert(verts, pt)                     -- low left
        table.insert(verts, pt + vec2(0,25))        -- high left
        table.insert(verts, pt + vec2(100,25))      -- high right
        
        table.insert(verts, pt + vec2(100,25))      -- high right
        table.insert(verts, pt + vec2(100,0))       -- low right
        table.insert(verts, pt)                     -- low left
    end
    m.vertices = verts
    m.texture = img

The texture doesn’t show, I guess I have to set the tex coords to spread it over all poly’s, but I’m not sure how to do that. I want the texture to draw once over all polygons.

It looks like you’re drawing a quad. Why not just use addRect and setRectTex? If you do want to calculate texcoords manually, convert your vert coords to the range 0 - 1. Something like:

local bounds = upperRight - lowerLeft -- where upperRight and lowerLeft are vec2s describing the maximum extent of the mesh
local texCoords = {}
for i,vert in ipairs(verts) do
    texCoords[i] = vec2( (vert.x - lowerLeft.x) / bounds.x, (vert.y -lowerLeft.y) / bounds.y)
end

@Kirl Here’s an example. I’ll let you correct your code.

function setup()
    img = readImage("Planet Cute:Icon")
    m=mesh()
    m.vertices = {vec2(0,0),vec2(100,0),vec2(0,100),
                    vec2(0,100),vec2(100,100),vec2(100,0)}
    m.texCoords = {vec2(0,0),vec2(1,0),vec2(0,1),
                    vec2(0,1),vec2(1,1),vec2(1,0)}
    m.texture = img
end

function draw()
    background(40, 40, 50)
    m:draw()
end

@Kirl Here’s an example using addRect.

function setup()
    img=readImage("Platformer Art:Block Grass")
    w=img.width
    h=img.height
    m=mesh()
    verts={}
    tex={}
    for i=1,4 do
        m:addRect(w*i,h,w,h)
    end
    m.texture="Platformer Art:Block Grass"
    sprite()
end

function draw()
    background(40, 40, 50)
    m:draw()
end

Thanks a lot guys! :slight_smile: