Creating Collision from 2D Texture (acquired from GetPixels)

Hi there, I am new to Unity, but hope to use it to create a simple 2D platformer-type game. I am wondering if anyone out there can tell me if what I am hoping to do would be possible, and if so any suggestions on how to go about it would be greatly appreciated.

What I want is for my Unity game to take a 2D Texture, analyse the colours in it, and apply collision to certain parts - applying collision where the colour is blue, for example. I understand the function GetPixels() can be used to ascertain the colour values of a group of pixels, but I am unsure about how I might go about using this to achieve what I want.

Thanks for any help! :slight_smile:

Hi,

I’ve done something similar before. When you create your texture with the game graphics you need to also create a duplicate of the same texture but using collision colours instead of the actual texture pixels.

For instance, in the game texture you might have a 16x16 tile with some earth and some grass on top. For the collision version you would have a 16x16 texture but filled with colours that specify what type of collision to use. I use black for no collision, white for normal collision, blue for water, red for damage etc…

In your game you need to read that texture in using GetPixels and convert it to an array of collision types for each game block. For instance, you might have a collision enum:

enum eCollisionType
{
none,
full,
water,
damage
}

and an array:

eCollisionType[,] CollisionArray = new eCollisionType[16,16];

Then loop through and do GetPixel:

Color PixelColour = GetPixel( x , y );

and convert to the enum type:

if( PixelColour == Color.black)
CollisionArray[×][y] = eCollisionType.none;
if( PixelColour == Color.white)
CollisionArray[×][y] = eCollisionType.full;

Once you’re array is set up you need to write your own code to check the collision pixel underneath the player (or wherever you want to check).

Cheers,T