Finding color of a body at the point of collision with another body?

Hi all,

I have a box collider attached to a body. Now whenever a ball comes in contact this body. I want to produce a particle effect that has the color of the point of contact on the box body. Note that am changing the texture of the box body at run time and the color I need should be based on the texture at the time of collision(ie the color of the texture, at the point of collision).

Thanks

take the RGB values of the main color of ur shader, compare and make a result color.

Sorry but thats not wat i want, I need the color of the texture

1 Answer

1

No code since I don’t have Unity running, but an idea that should work:

  1. Take a contact point _cp (collision.contacts returns a ContactPoint … pick one)

  2. Do a raycast from _cp.point+_cp.normal to _cp.point

  3. The RaycastHit object gives you the object’s renderer (and through that the Texture2D) and the UV coordinate (hit.textureCoord).

  4. Now you can simply use texture.GetPixel(texCoord.x * texture.width, texCoord.y * texture.height) to get the color.

Hope this makes sense. For the raycasting part, you can have a look at that example: http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit-textureCoord.html

But does this work for box and sphere collider?

I don't see why not. The 2 problems I can see are: 1) if your colliders are too different from the actual object (not a problem if you're actually using a box and a sphere) 2) if there is something blocking the raycast. Put all your blocks on a separate layer and use the layer parameter in your raycast function and you should be fine.