Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Changing of a material at Contact Point

Discussion in 'Scripting' started by Black-pearl, Dec 21, 2015.

  1. Black-pearl

    Black-pearl

    Joined:
    Mar 20, 2014
    Posts:
    55
    Hey Everyone,

    I am struggling a little bit with this one, basically what I want to do is when my projectile hits an object I want to change the material at the hit point and then fade it. I have managed to get the hit point of the object but I cannot seem to change the material at that point. I only want to say change a small radius of the objects material not the whole object, see below for the bit of script I have already,

    Code (CSharp):
    1. if(col.gameObject.tag == "ContactTest")
    2.         {
    3.             ContactPoint contact = col.contacts[0];
    4.             Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
    5.             Vector3 pos = contact.point;
    6.             Debug.Log("---------------");
    7.             Debug.Log("Contact point " + contact.point);
    8.             Destroy(gameObject);
    9.         }
    10.  
    Hope you guys can help :)

    Thanks in advance
     
  2. kietus

    kietus

    Joined:
    Jun 4, 2013
    Posts:
    54
    Hello,

    I don't think there an easy way to do that. That's also depending the type of material and shader you use, and your final objective.
    One way could be to use decals, i don't know if that can match your solution. There some existing plugin. Basically it will create a mini mesh with a dedicated texture. So you can apply a sort of texture patch on your object at the hit point.

    If you really want to change the material for only a part of the object a solution could be to use a vertex color shader. Or to re arrange the mesh so a part of it is rendered with another material.
    In both case you will need to find the vertices (meshfilter.mesh.vertices) affected by the impact radius. if i'm not mistaken contactPoint give you collision point between colliders, you can't change material with that.
    But from the hit.point, you can define a radius and search for a vertices in the zone.

    a solution with a color vertex shader will involve changing the vertex.color value in the impact zone (easy blending capability). another can be to swap triangles rendered with material 1 to another submesh, so they can be rendered with a material 2 (see meshfilter.mesh.SetTriangles(newTriangles, submeshIndex)), blending seems harder with that solution.

    if there an easier solution, i don't know it : )