Unity 射线碰撞检测

项目原由:

前段时间项目须要完成一个点击,拖动,缩放功能。并无使用Ngui或者Ugui自带的手势识别的功能,是直接在Update中处理了这些事务。可是后来根据项目需求添加了一个按钮(其实为一个Sprite),发现点击事件与按钮的事件是相互冲突的。缘由应该是Update是获取的屏幕的事件是和按钮同级别的,因此须要修改。最后使用的是射线碰撞检测。c#

1.射线检测原理:

  • 获取屏幕点击点的位置
  • 从主摄像机做出射线到屏幕点击点
  • 使用RayCast函数计算

2.代码实现:

首先对须要被检测的物体添加碰撞器。ide

Ray buttonRay;
RaycastHit myRayHit
void Update(){
    if (Input.touches.Count > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) {
        //若是场景中存在多个摄像头,须要定义是哪一个Camera。通常是用UI的那个。
        buttonRay = Camera.main.ScreenPointToRay (Input.GetTouch(0).position); 
        //用来划线
        //Debug.DrawLine (buttonRay.origin, myRayHit.point, Color.red, 2); 
 	    if (Physics.Raycast(buttonRay, out myRayHit){
 	        //这里能够经过myRayHit来获取碰撞到的东西。
 	        Debug.Log ("按钮");
        }else{
            Debug.Log ("点击");
        }
}

3.关键函数:

从摄像头到position的射线: {% highlight c# %} public Ray ScreenPointToRay(Vector3 position); {% endhighlight %}函数

检测在这个射线中碰撞到碰撞器ui

/*
Returns bool
bool True if the ray intersects with a Collider, otherwise false.
*/
public static bool Raycast(
        Vector3 origin, 
        Vector3 direction, 
        float maxDistance = Mathf.Infinity, 
        int layerMask = DefaultRaycastLayers, 
        QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

4.总结:

事实上射线碰撞也能够用在游戏中物体的拾取判断,这里原理是同样的我就不作例子了。对于手势的处理我以为不该该放在update中处理,应该好好利用NGUI这些插件。固然多懂些原理也并无什么坏处。插件

相关文章
相关标签/搜索