RayCast in unity C#

421 Views Asked by At

I'm trying to use a raycast in unity that only reflect off of an objects i define but it didn't work with me any help please? my game is laser reflection so it's not like a shooting game i need the laser to be visible the whole time and i only Need the laser to be reflected off of the mirrors and not the walls, not the floor nor the other objects in the room. i tried this code.

public class RaycastReflection : MonoBehaviour
{
    public int gunDamage = 1;
    public float hitForce = 1f;
    private Transform goTransform;
    private LineRenderer lineRenderer;
    private Ray ray;
    private RaycastHit hit;
    private Vector3 inDirection;
    public int nReflections = 2;
    private int nPoints;

    void Awake()
    {

    }

    void Update()
    {      
        nReflections = Mathf.Clamp(nReflections, 1, nReflections);
        ray = new Ray(goTransform.position, goTransform.forward);
        nPoints = nReflections;

        lineRenderer.SetVertexCount(nPoints);
        lineRenderer.SetPosition(0, goTransform.position);

        for (int i = 0; i <= nReflections; i++)
        {
            //If the ray hasn't reflected yet  
            if (i == 0)
            {
                //cast the ray 100 units at the specified direction  
                if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))
                {  
                    inDirection = Vector3.Reflect(ray.direction, hit.normal);
                    ray = new Ray(hit.point, inDirection);

                    if (nReflections == 1)
                    {
                        lineRenderer.SetVertexCount(++nPoints);
                    }

                    lineRenderer.SetPosition(i + 1, hit.point);
                }
            }
            else 
            {
                if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))
                {
                    Target health = hit.collider.GetComponent<Target>()
                    if (health != null)

                    health.Damage(gunDamage);

                    if (hit.rigidbody != null)
                        hit.rigidbody.AddForce(-hit.normal * hitForce);

                    inDirection = Vector3.Reflect(inDirection, hit.normal);
                    ray = new Ray(hit.point, inDirection);

                    lineRenderer.SetVertexCount(++nPoints);
                    lineRenderer.SetPosition(i + 1, hit.point);
                }
            }
        }
    }
}
0

There are 0 best solutions below