您的位置:首页 > 移动开发 > Unity3D

Unity Ray 射线检测

2015-06-26 16:29 465 查看
首先在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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: