2013-05-08 37 views
5

请参阅下面的图像。在Unity中检查接触点是否在箱式对撞机中

enter image description here

enter image description here

在第一个图像,你可以看到有箱撞机。 第二图像是当我运行Android装置

这里上的代码被我想看看是否触摸点是内部的,其附接至玩游戏的代码(其三维文本)

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); 
       } 
      }     
     } 
    } 
} 

对撞机还是不对。我想这样做,因为现在如果我点击任何场景 Application.LoadLevel(levelToLoad);叫做。

我想要它被调用,如果我只点击玩游戏文本。任何人都可以帮助我使用这段代码,或者可以给我另一种解决方案来解决我的问题?


通过以下Heisenbug的逻辑

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);    
     }   
    } 
} 
} 

回答

5

Touch的位置在屏幕空间坐标系表示(一个Vector2)最近的代码。您需要在世界空间坐标系中转换该位置,然后尝试将其与场景中对象的其他3D位置进行比较。

Unity3D提供设施来做到这一点。由于您使用的是BoundingBox围绕你的文字,你可以执行以下操作:

  • 创建Ray其起源是在触摸点位置和方向平行于摄像机向前轴(Camera.ScreenPointToRay)。
  • 检查该射线是否与您的GameObjectPhysic.RayCast)的BoundingBox相交。

代码可能看起来类似的东西:

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. 
} 

它的方便一个特定的层添加到您的“玩游戏” GameObject,为了使光线只能与其碰撞。


EDIT

代码和上述的说明是正常。如果你没有得到适当的碰撞,也许你没有使用正确的层。我目前没有触摸设备。以下代码可以使用鼠标(不使用图层)。

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"); 
      } 

     } 
    } 

} 

这只是一个例子,可以让您朝正确的方向发展。试着找出你的情况出了什么问题或发布SSCCE

+0

我所做的就是选定的三维文字,并在检查员中选择指定的图层。层数为8.之后,我传递参数layerOfYourGameObject为8并运行代码,但仍未发生碰撞。我在上面的问题中附加了代码。 – 2013-05-09 06:00:33

+0

如果我错误地指出如何将图层添加到3D文字,请纠正我的错误。 1)选择三维文字。 2)在Inpector前往AddLayer并将Unity Layer 10命名为PlayGameLayer。 3)在督察标记=无标记和层= PlayGameLayer。 4)带有上述代码的脚本附加到PlayGame3D文本中。 这是正确的方式吗?如果是这样,那可能是什么错误? – 2013-05-10 06:14:25

+0

@Jawad Amjad:您是否将边界框附加到已添加文本组件的相同GameObject? – Heisenbug 2013-05-10 20:56:59

相关问题