Here is a better one that let’s you use the texture width and height or the polygon width and height. I also renamed the highX and highY variables to polyWidth and polyHeight:
-- vec2 test
displayMode(FULLSCREEN)
function setup()
sampletexture1 = readImage("Platformer Art:Block Special")
sampletexture2 = readImage("Platformer Art:Block Grass")
box=physics.body(POLYGON,vec2(0,0),vec2(0,100),vec2(100,100),vec2(100,0))
box.x=WIDTH/2
box.y=HEIGHT/2
floor=physics.body(POLYGON,vec2(0,0),vec2(0,10),vec2(1024,10),vec2(1024,0))
floor.type=STATIC
floor.x=0
floor.y=0
box2=physics.body(POLYGON,vec2(0,0),vec2(0,100),vec2(100,100),vec2(100,0))
box2.x=412
box2.y=0
box3=physics.body(POLYGON,vec2(0,0),vec2(0,100),vec2(100,100),vec2(100,0))
box3.x=612
box3.y=0
box4=physics.body(POLYGON,vec2(0,0),vec2(0,50),vec2(300,50),vec2(300,0))
box4.x=412
box4.y=760
box5=physics.body(POLYGON,vec2(0,0),vec2(0,50),vec2(50,50),vec2(50,0))
box5.x=500
box5.y=600
box5.restitution=0.7
shape=physics.body(POLYGON,vec2(0,0),vec2(0,50),vec2(25,75),vec2(50,50),vec2(50,0))
shape.x=420
shape.y=600
shape.restitution=0.7
end
function polygon(p,texture,polyWidth,polyHeight)
pushMatrix()
translate(p.x, p.y)
rotate(p.angle)
local m = mesh()
m.vertices = triangulate(p.points)
m.texture = texture
local coords = {}
local w,h
if polyWidth ~= nil and polyHeight ~= nil then
w,h = polyWidth,polyHeight
else
w,h = texture.width,texture.height
end
for i,v in ipairs(m.vertices) do
coords[i] = vec2(v.x/w,v.y/h)
end
m.texCoords = coords
m:draw()
popMatrix()
end
function polygonWireframe(p)
pushMatrix()
translate(p.x, p.y)
rotate(p.angle)
for i = 1, #p.points do
local a = p.points[i]
local b = p.points[(i % #p.points)+1]
line(a.x, a.y, b.x, b.y)
end
popMatrix()
end
function rectangle(p)
pushMatrix()
pushStyle()
translate(p.x, p.y)
rotate(p.angle)
rectMode(CORNERS)
rect(p.points[1].x, p.points[1].y, p.points[3].x, p.points[3].y)
popStyle()
popMatrix()
end
function draw()
background(255, 255, 255, 255)
pushStyle()
fill(25, 0, 255, 255)
stroke(25, 0, 255, 255)
strokeWidth(2)
rect(floor.x,floor.y,1024,10)
polygonWireframe(box)
rectangle(box2)
rectangle(box3)
popStyle()
polygon(box4,sampletexture1,300,50)
polygon(box5,sampletexture1)
polygon(shape,sampletexture2)
end
To use the texture width and height, leave polyWidth and polyHeight blank as I did for box5 and shape. To stretch the texture to fit the whole polygon, you must then fill in polyWidth and polyHeight like I did for box4.
Hope this helps. You should be able to put a texture onto any polygon no matter the shape or size using the polygon function.