# What is the easiest way to convert raycasthit2D to pixel coordinates?

I have a sprite with a box collider or polygon collider and I’m looking for a calculation that will translate any raycasthit2D on that sprite into the pixel coordinates of the texture so I can use the coordinates with GetPixel().

Does anyone have some code that will do this conversion?

There are quite a few posts on similar topics but nothing that has solved my issue. Someone had suggested translating the hit into barycentric coordinates, but I’m not great with maths and it blew my mind a little bit. My project’s at a standstill while I have this issue so any help will be appreciated massively

Thanks!

Romano

Considering you will hit on the edges of the sprite, you can take the position of the hit, find the local position of that hit, simply doing

LocalPos= sprite.position-hit.position

Then you can convert that local position into texture position using the width and height of it.

Uv = localPos.y/ height *textureHeight

This is considering you hit the side of it.

This is simplified but maybe you get something out of it.

EDIT:
You turn the hit point to local position of the sprite. Then you do the process of conversion for both dimensions (x and y).

All you do is converting from one coordinate to another. For instance, if you have a sprite that has dimensions 2x2 at position (10,1)and you hit at position (9.5,0.5). Your texture is a 256x256.

First get the hit in sprite position:

10 - 9.5 = 0.5
1 - 0.5 = 0.5

Turn that into texture coordinates:

value * scale * textureSize
uv.x = 0.5 / 2 * 256 -> 64
uv.y = 0.5 / 2 * 256 -> 64

64,64 is the pixel position of your hit.