I’m programming a game and I want to collide images with transparent borders (sprites) against a circle.
It’s easy to know if the circle is overlapping the image by checking collision with the pixels which are not transparent.
The problem I have is to know the normal angle in order to make a bounce.
I would need a library (Java) or algorithm that given an image it would return an array with the pixels that are at the border of the image so i can find the slope between two points of the surface.
Is there any library/algorithm/code snippet i can learn from?
Here’s a simple approach:
Create a mask from the original image where all transparent pixels are
0and all non-transparent pixels are1Then, perform a simple edge detection on your mask by subtracting each pixel
(x,y), which will be0or1, from pixel(x+1,y+1)and taking the absolute value.This will give you a
1for pixels on the edge of the image and a0everywhere else.Note: this method is essentially equivalent to treating the image as a 2d function and calculating its gradient. The edges are steep parts of the intensity surface (which correspond to large gradient values). Here’s some more information on gradient-based edge detection.
Here’s an example image:
First mask all the non-transparent pixels:
Then shift the image down and over one pixel and subtract it from itself.
This creates the image below. Now simply read out the matrix indices with value
1.That’s your array of edge pixels.
Note: if your images contain interior transparent pixels, this technique will also find interior edges, which may or may not be a problem for you…