Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Applying texture to mesh?

in Questions Posts: 181

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.

Tagged:

Comments

  • edited August 2016 Posts: 2,020

    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
    
  • dave1707dave1707 Mod
    Posts: 7,675

    @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
    
  • dave1707dave1707 Mod
    Posts: 7,675

    @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
    
  • Posts: 181

    Thanks a lot guys! :)

Sign In or Register to comment.