使用RayCastAll代替RayCast

时间:2019-07-03 08:48:07

标签: unity3d

我有两个游戏对象滚子和标记物。当我使用物理raycast时,它可以工作,但是使用raycastall时,它不能。我需要使用raycastall,因为我需要遍历对撞机。当标记器位于滚轴上时,正常的raycast无法正常工作,我需要使用raycastall。

此代码有效:

if (Input.touchCount > 0)
{
    // get mouse position in screen space
    // (if touch, gets average of all touches)
    Vector3 screenPos = Input.mousePosition;
    // set a distance from the camera
    screenPos.z = 10.0f;
    // convert mouse position to world space
    Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    Physics.Raycast(cameraRay, out hit);
    if (hit.collider.tag == "Floor")
    {
        transform.position = hit.point;
    }

    /*
    Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
    // get current position of this GameObject
    Vector3 newPos = transform.position;
    // set x position to mouse world-space x position
    newPos.x = worldPos.x;
    newPos.z = worldPos.z-3f;
    // apply new position
    transform.position = newPos;
    */

    if (Input.GetTouch(0).phase == TouchPhase.Ended)
    {
        Destroy(gameObject);
        touchhandler = GameObject.Find("Roller").GetComponent<TouchHandler>();
        touchhandler.markerexists = false;
    }
}

这不是:

if (Input.touchCount > 0)
{
    // get mouse position in screen space
    // (if touch, gets average of all touches)
    Vector3 screenPos = Input.mousePosition;
    // set a distance from the camera
    screenPos.z = 10.0f;
    // convert mouse position to world space
    Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit[] hits;
    hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0F);
    while (i < hits.Length)
    {
        RaycastHit hit = hits[i];
        if (hit.collider.tag == "Floor") 
        {
            transform.position = hit.point;
        }

        i++;
    }

    if (Input.GetTouch(0).phase == TouchPhase.Ended)
    {
        Destroy(gameObject);
        touchhandler = GameObject.Find("Roller").GetComponent<TouchHandler>();
        touchhandler.markerexists = false;
    }
}

0 个答案:

没有答案