请看下面的图片。
在第一张图片中,您可以看到有一个盒子碰撞器。 第二张图是我在安卓设备上运行代码的时候
这是附加到 Play Game 的代码(它是一个 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);
}
}
}
}
}
我想看看触摸点是否在对撞机内部。我想这样做是因为现在如果我点击场景中的任何地方 Application.LoadLevel(levelToLoad);叫做。
我希望仅在单击 PLAY GAME 文本时调用它。任何人都可以帮助我处理这段代码或者可以为我的问题提供另一种解决方案吗??
遵循 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);
}
}
}
}
最佳答案
触摸的位置在屏幕空间坐标系(Vector2
)中表示。在尝试将其与场景中对象的其他 3D 位置进行比较之前,您需要在世界空间坐标系中转换该位置。
Unity3D
提供了执行此操作的工具。由于您在文本周围使用 BoundingBox
,因此您可以执行以下操作:
- 创建一个
Ray
,原点在触摸点位置,方向平行于相机前轴 (Camera.ScreenPointToRay)。 - 检查该射线是否与您的
GameObject
(Physic.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
很方便,以使光线仅与其发生碰撞。
编辑
上面的代码和解释很好。如果你没有得到正确的碰撞,可能你没有使用正确的层。我目前没有触摸设备。以下代码适用于鼠标(不使用图层)。
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 .
关于android - 检查触摸点是否在 Unity 中的盒子碰撞器内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442728/