Unity3D自学笔记——选择3D物体

  • 效果图

 Unity3D自学笔记——选择3D物体_第1张图片


  • 思路
  1. 建筑物体添加刚体组件
  2. 通过射线来判断物体是否被选中
  3. 选中后执行物体的选中事件,出现魔法阵

 

  • 实现

 

  1.  给物体添加Box Collider并添加Building

Unity3D自学笔记——选择3D物体_第2张图片

 

  1. Building代码

	public class Building : MonoBehaviour {
	    private GameObject m_MagicImage;
	    private Material m_Image;
	    private Tweener m_Tween;
	    private bool m_IsSelected;
	
	    void Awake()
	    {
	        m_MagicImage = Global.FindChild(transform, "MagicImage");
	        m_Image = m_MagicImage.GetComponent().materials[0];
	    }
	
	    void Start()
	    {
	        //魔法阵颜色ALPH变化
	        m_Tween = DOTween.ToAlpha(() => m_Image.color, x => m_Image.color = x, 0.8f, 0.5f).SetLoops(-1).Pause();
	    }
	
	    void Update()
	    {
	        if (m_IsSelected)
	        {
	            m_MagicImage.SetActive(true);
	            //魔法阵旋转
	            m_MagicImage.transform.Rotate(new Vector3(0, 1, 0), 10 * Time.deltaTime, Space.World);
	            //魔法阵颜色ALPH变化
	            m_Tween.Play();
	        }
	        else
	        {
	            if (m_Tween != null)
	                m_Tween.Pause();
	
	            m_MagicImage.SetActive(false);
	        }
	    }
	
	    public void SelectThis(bool isSelected)
	    {
	        m_IsSelected = isSelected;
	    }
	}


 

  1. 摄像机添加代码,将建筑问题都将Tag标记为"building"

 

	public class CameraManager : MonoBehaviour {
	    void Update()
	    {
	        if (Input.GetMouseButtonDown(0))
	        {
	            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	            RaycastHit hit;
	
	            if(Physics.Raycast(ray, out hit))
	            {
	                if(hit.transform.tag == "Building")
	                {
	                    hit.transform.gameObject.GetComponent().SelectThis(true);
	                }
	            }
	        }
	    }
}


你可能感兴趣的:(Unity3D,unity3d)