首先在PC端实现鼠标点击某个物体执行某个操作时我们用Input.GetMouseButtonDown(0),获取鼠标点击事件。
再通过Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition)获取鼠标点击屏幕的坐标。
最后判定该坐标是否点击到某个物体:
if(Physics.Raycast(ray,out hit,1000f)
{
if(hit.collider.name==" ")
执行对应操作。
}
具体代码如下:
// 桌面系统鼠标操作
void DesktopInput()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000f))
{
hitname = hit.collider.name;
if (hitname == "moviePlayerCtl")
{
moviePlayer.gameObject.SetActive(true);
maincamer.GetComponent<PosStateRecord>().location("org");
goodsShower.gameObject.SetActive(false);
}
else if (hitname == "showsOnline")
{
maincamer.GetComponent<PosStateRecord>().location("ui");
moviePlayer.gameObject.SetActive(false);
goodsShower.gameObject.SetActive(true);
}
}
}
}
在移动平台操作时,由于没有鼠标,只能用手触屏,所以需要把
if(Input.GetMouseButtonDown(0))改成if(Input.touchCount>0)
触屏坐标的取值方式改成Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position)
移动平台触屏代码如下:
//移动平台触屏操作
void MobileInput()
{
if (Input.touchCount >0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position );
if (Physics.Raycast(ray, out hit, 1000f))
{
hitname = hit.collider.name;
if (hitname == "moviePlayerCtl")
{
moviePlayer.gameObject.SetActive(true);
maincamer.GetComponent<PosStateRecord>().location("org");
goodsShower.gameObject.SetActive(false);
}
else if (hitname == "showsOnline")
{
maincamer.GetComponent<PosStateRecord>().location("ui");
moviePlayer.gameObject.SetActive(false);
goodsShower.gameObject.SetActive(true);
}
}
}
}
最后,如果想实现多平台性只需要在Update中检测是哪个平台,再对应调用该平台需要的方法即可:
void Update()
{
#if !UNITY_EDITOR && ( UNITY_IOS || UNITY_ANDROID )
MobileInput();
#else
DesktopInput();
#endif
}
|