How to calculate the pixel colors of an image ??
-
- Prole
- Posts: 21
- Joined: Tue Mar 07, 2023 11:01 pm
How to calculate the pixel colors of an image ??
I have an image and I'm trying to get the pixel values of the image, I want my player to collide with the image based on the value of the pixel can someone please show me how to do that and how to act upon knowing the pixels. I just thought of this idea, for me to calculate the pixel value of the entire canvas and then say if the value of a pixel was 225 then collide with it. but I want it to collide only with the image so I pretty much need to calculate the pixels of the image, but I'm not sure how to do that ... any help would be greatly appreciated
Re: How to calculate the pixel colors of an image ??
Please use the Support and Development subforum for questions. This subforum is for showcasing your games and creations.
Re: How to calculate the pixel colors of an image ??
This can be a costly operation so here is how you could do it:
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.
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
- Attachments
-
- PixelPerfect.love
- (3.72 KiB) Downloaded 79 times
Who is online
Users browsing this forum: No registered users and 3 guests