Raycast doesn't work properly

2019-09-02 02:07发布

I'd like to get the neighbors of the box by raycasting, but it's working only left and down directions. Could you help me, why is it not getting the neighbors of right and up directions? thanks

All boxes in grid[x,y]:

o - is box.

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

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

标签: unity3d
2条回答
时光不老,我们不散
2楼-- · 2019-09-02 02:21

From unity docs:

If you move colliders from scripting or by animation, there needs to be at least one FixedUpdate executed so that the physics library can update its data structures, before a Raycast will hit the collider at it's new position.

It helped me.

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

查看更多
一纸荒年 Trace。
3楼-- · 2019-09-02 02:32

You are using Vector3, which is 3D, in a 2D matrix.

查看更多
登录 后发表回答