想实现鼠标点击屏幕时,创建物体,并且物体跟随鼠标移动,UI跟随鼠标移动,NGUI里已经有脚本可以实现这一点(UIDragDropItem ),在这里就不多说。这里主要说一下鼠标点击屏幕创建物体。
下面是我写的一些代码:
ray = UICamera.mainCamera.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButton(0))
{
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.GetComponent<ShowObjectName>()) return;
_VectorScreenPos = _trans.InverseTransformPoint(hit.point);//转相对于UIRoot的相对坐标(绝对坐标转相对坐标,也就是世界坐标转你想要放到的父节点下的相对坐标)
tempName = readDate.GetLabelName(GetCount());
if (!dicUI.ContainsKey(tempName))
{
clone = Instantiate(prefab) as UISprite;
clone.name = "sprite";
clone.transform.parent = _trans;
clone.GetComponent<ShowObjectName>().ShowLabelName(tempName);
dicUI.Add(tempName, clone);
}
dicUI[tempName].transform.localPosition = _VectorScreenPos;
dicUI[tempName].transform.localRotation = Quaternion.Euler(Vector3.zero);
dicUI[tempName].transform.localScale = Vector3.one;
}
}
其中最主要的是InverseTransformPoint函数把物体的绝对坐标转为相对坐标,这里是把射线碰到的点转为了UIRoot下的相对坐标,再把此坐标赋予创建的物体,从而实现,点击创建