Unity3D开发之放大效果的实现

    demo效果如下图:


    实现思路:1.发射射线判断是否碰撞以及获取和模型碰撞的点。

                    2.根据是否碰撞设置是否显示放大效果Panel。

                    3. 将碰撞点坐标转换到屏幕坐标 设置Panel位置。

                    4.创建一个专门用于旋转放大细节的摄像机,输出的贴图放到Panel上。根据碰撞点位置设置摄像机的位置。

    我们项目多个场景时会经常用到射线检测,所以我们把射线检测相关的方法以及获取到的值封装到一个类里,供全局调用。代码如下:

using UnityEngine;

public class RayObject{

    private Camera maincamera;
    private RaycastHit hit;
    private string tag = "Model";
    private Vector3 rayPoint;

    public GameObject RayGameOb { get { return GetRayGameObject(); } }

    public bool IsRayGameOb { get { return IsRayGameObject(); } }

    public Vector3 RayPoint { get { return rayPoint; } }

    public RayObject(Camera camera,string name)
    {
        maincamera = camera;
        tag = name;
    }

    //获取被射线检测到的物体
    private GameObject GetRayGameObject()
    {
        Ray ray = maincamera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.CompareTag(tag))
            {
                rayPoint = hit.point;
                return hit.collider.gameObject;
            }
            return null;
        }
        return null;
    }

    //是否射到指定物体上
    private bool IsRayGameObject()
    {
        Ray ray = maincamera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.CompareTag(tag))
            {
                rayPoint = hit.point; return true;
            }
            return false;
        }
        return false;
    }
}

然后,我们创建一个挂载于场景上运行开启的脚本,代码如下:

public class MagnifyEffect : MonoBehaviour {

    [SerializeField]
    private GameObject MagnifyPanel;
    [SerializeField]
    private Camera MagnifyCamera;
    RayObject rayObject;
    private RectTransform canvas;
    // Use this for initialization
    void Start () {
        rayObject = new RayObject(Camera.main,"Model");
        canvas = GameObject.Find("Canvas").GetComponent();
    }
	
	// Update is called once per frame
	void Update ()
    {
        if(rayObject.IsRayGameOb)
        {
            MagnifyPanel.SetActive(true);
            Vector2 pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,Input.mousePosition,null,out pos);
            MagnifyPanel.transform.localPosition = pos;
            //print(rayObject.RayPoint);
            Vector3 cameraPos = MagnifyCamera.transform.position;
            MagnifyCamera.transform.position = new Vector3(rayObject.RayPoint.x, rayObject.RayPoint.y, cameraPos.z);
        }
        else
        {
            MagnifyPanel.SetActive(false);
        }
    }

    
}
    以上就是实现的代码。对于Camera输出的贴图设置参考之前博客,模型显示在UI前面有讲对于贴图的设置。希望对你有帮助。

你可能感兴趣的:(Unity)