This can be a costly operation so here is how you could do it:
Code: Select all
local function checkCollision(img_data1,x1,y1,w1,h1, img_data2,x2,y2,w2,h2)
-- Calculate the coordinates of the corners of the two objects
local left1, top1, right1, bottom1 = x1, y1, x1 + w1, y1 + h1
local left2, top2, right2, bottom2 = x2, y2, x2 + w2, y2 + h2
-- Check if there is an intersection between the two objects
if right1 > left2 and left1 < right2 and bottom1 > top2 and top1 < bottom2 then
-- Calculate the intersection area between the two objects
local intersectionLeft = math.max(left1, left2)
local intersectionTop = math.max(top1, top2)
local intersectionRight = math.min(right1, right2)
local intersectionBottom = math.min(bottom1, bottom2)
local floor = math.floor
-- Iterate through all pixels in the intersection area
for x = intersectionLeft, intersectionRight-1 do
for y = intersectionTop, intersectionBottom-1 do
-- Calculate pixel coordinates in both images
local playerPixelX, playerPixelY = floor(x-x1), floor(y - y1)
local obstaclePixelX, obstaclePixelY = floor(x-x2), floor(y-y2)
-- Check if both pixels are opaque
local _,_,_,a1 = img_data1:getPixel(playerPixelX, playerPixelY)
local _,_,_,a2 = img_data2:getPixel(obstaclePixelX, obstaclePixelY)
if a1 > 0 and a2 > 0 then return true end
end
end
end
return false
end
It is only as an example to get an idea, this function does not manage for example the replacement of objects following the collision, and it only works with an image origin set to 0.0. If the coordinate sent represents for example the center of the image it will also have to be modified a little.