检查触摸点是否在Unity中的盒子对撞机内

Jaw*_*jad 5 android unity-game-engine game-physics

请看下面的图片.

在此输入图像描述

在此输入图像描述

在第一张图片中,您可以看到有箱式对撞机.第二个图像是我在Android设备上运行代码的时候

这是附加到Play游戏的代码(它是一个3D文本)

using UnityEngine;
using System.Collections;

public class PlayButton : MonoBehaviour {   

    public string levelToLoad;
    public AudioClip soundhover ;
    public AudioClip beep;
    public bool QuitButton;
    public Transform mButton;
    BoxCollider boxCollider;

    void Start () {
        boxCollider = mButton.collider as  BoxCollider;
    }

    void Update () {

        foreach (Touch touch in Input.touches) {

            if (touch.phase == TouchPhase.Began) {

                if (boxCollider.bounds.Contains (touch.position)) {
                    Application.LoadLevel (levelToLoad);
                }
            }                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道碰撞点是否在碰撞器内部.我想这样做是因为我现在点击场景中的任何位置Application.LoadLevel(levelToLoad); 叫做.

如果我点击播放游戏文本,我希望它被调用.任何人都可以帮我解决这段代码,还是可以给我另一个解决问题的方法?


最近的守则遵循海森堡的逻辑

void Update () {

foreach( Touch touch in Input.touches ) {

    if( touch.phase == TouchPhase.Began ) {

        Ray ray = camera.ScreenPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, Mathf.Infinity, 10)) {
            Application.LoadLevel(levelToLoad);             
        }           
    }   
}
}
Run Code Online (Sandbox Code Playgroud)

Hei*_*bug 5

触摸的位置以屏幕空间坐标系(a Vector2)表示.在尝试将其与场景中对象的其他3D位置进行比较之前,您需要在世界空间坐标系中转换该位置.

Unity3D提供这样做的设施.由于您使用的是BoundingBox文本周围,因此可以执行以下操作:

  • 创建Ray哪个原点位于触摸点位置,哪个方向与摄像机前进轴平行(Camera.ScreenPointToRay).
  • 检查该光线是否与BoundingBox您的GameObject(Physic.RayCast)相交.

代码可能看起来像这样:

Ray ray = camera.ScreenPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerOfYourGameObject))
{
   //enter here if the object has been hit. The first hit object belongin to the layer "layerOfYourGameObject" is returned.
}
Run Code Online (Sandbox Code Playgroud)

在"Play游戏"中添加特定图层会很方便GameObject,以便使光线仅与其发生碰撞.


编辑

上面的代码和解释很好.如果你没有得到正确的碰撞,也许你没有使用正确的层.我目前还没有触控设备.以下代码适用于鼠标(不使用图层).

using UnityEngine;
using System.Collections;

public class TestRay : MonoBehaviour {

    void Update () {

        if (Input.GetMouseButton(0))
        {
            Vector3 pos = Input.mousePosition;
            Debug.Log("Mouse pressed " + pos);

            Ray ray = Camera.mainCamera.ScreenPointToRay(pos);
            if(Physics.Raycast(ray))
            {
                Debug.Log("Something hit");
            }

        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这只是让你走向正确方向的一个例子.试着弄清楚你的情况出了什么问题或发布了SSCCE.