Raycast无法正常工作

时间:2015-03-05 09:33:21

标签: unity3d

我想通过光线投射来获得盒子的邻居,但它只能在左右方向上工作。你可以帮助我吗,为什么不能让邻居向右和向上指示?谢谢

网格[x,y]中的所有框:

o - 是盒子。

[-----------]

o o o o

o o o o

o o o o

o o o o

[----------]

...
    rLeft = new Ray(this.transform.position, Vector3.left);
    rRight = new Ray(transform.position, Vector3.right);
    rUp = new Ray(transform.position, Vector3.up);
    rDown = new Ray(transform.position, Vector3.down);

    GetNeigbor(rUp); // not work
    GetNeigbor(rLeft); //worked
    GetNeigbor(rRight); //not work
    GetNeigbor(rDown); //worked
}

void GetNeigbor(Ray ray)
{
    if (Physics.Raycast(ray, out _rayHit, 40) /*&& _rayHit.transform.tag == "MatchBox"*/)
    {
        neigbors.Add(_rayHit.collider.gameObject);
    }
}

2 个答案:

答案 0 :(得分:1)

来自团结文档:

  

如果您从脚本或动画中移动碰撞者,需要   成为至少一个执行的FixedUpdate 即物理库   可以在Raycast击中对撞机之前更新其数据结构   在它的新位置。

它帮助了我。

IEnumerator RefreshNeighbors()
{
    bool isRefreshing = true;

    while(isRefreshing)
    {
        yield return new WaitForEndOfFrame();
        FindNeighbors();
        isRefreshing = false;
    }
}

.. ..

public void FindNeighbors()
{
    neigbors.Clear();

    Ray rLeft = new Ray(this.transform.position, Vector3.left);
    Ray rRight = new Ray(this.transform.position, Vector3.right);
    Ray rUp = new Ray(this.transform.position, Vector3.up);
    Ray rDown = new Ray(this.transform.position, Vector3.down);

    FindNeighbor(rDown);
    FindNeighbor(rLeft);
    FindNeighbor(rUp);
    FindNeighbor(rRight);
}

void FindNeighbor(Ray ray)
{
    if (Physics.Raycast(ray, out _rayHit, 10) && _rayHit.transform.tag == "MatchBox")
    {
        if (Mathf.Abs(Ypos - _rayHit.transform.localPosition.y) > 1 || Mathf.Abs(Xpos - _rayHit.transform.localPosition.x) > 1)
        {
            //ignore neighbors which too far
            return;
        }
        else
        {
            neigbors.Add(_rayHit.transform.GetComponent<MatchedBox>());
        }
    }
}

http://docs.unity3d.com/ScriptReference/Physics.Raycast.html

答案 1 :(得分:0)

您正在2D矩阵中使用3D的Vector3。