u3d目标与摄像机之间的遮挡物变为透明

2023-08-24 13:38:48 浏览数 (2)

摄像机和目标物体连接一个射线,然后射线碰到的物体的Transparent/Diffuse全部设为半透明

代码语言:javascript复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class XrayCameral : MonoBehaviour {

    public Transform tar;
    public List<Renderer> listLastRend = new List<Renderer>();
    // Use this for initialization
    void Start () {

        
	}
	
	// Update is called once per frame
	void Update () {
        
        for (int i = 0; i < listLastRend.Count; i  )
        {
            TransparencySet(listLastRend[i], 1.0f);
        }
        listLastRend.Clear();
        Vector3 tarDir = (tar.position - transform.position).normalized;
        Debug.DrawLine(tar.position, transform.position, Color.red);

        float tarDis = Vector3.Distance(tar.position, transform.position);
        RaycastHit[] listHitObj = Physics.RaycastAll(transform.position, tarDir, tarDis);
        Debug.Log(listHitObj.Length);
        for (int i = 0; i < listHitObj.Length; i  )
        {
            RaycastHit hit = listHitObj[i];
            if (hit.transform == tar.transform)
            {
                continue;
            }
            Renderer renderer = hit.collider.GetComponent<Renderer>();

            if (renderer)
            {
                listLastRend.Add(renderer);
                TransparencySet(renderer,0.3f);
            }
        }

    }

    void TransparencySet(Renderer renderer,float a)
    {
        renderer.material.shader = Shader.Find("Transparent/Diffuse");
        renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, a);
    }
}

0 人点赞