如何racast 3D世界到屏幕(unity3d)

时间:2017-06-02 09:55:02

标签: unity3d unity5

在我的拍摄方法中,我正好在屏幕中间进行光线投射,工作正常,但现在为了更合适,我想在世界中将其更改为屏幕(以及交叉头发之间,而不是屏幕中间)。但我没有得到任何指示。在此先感谢您的帮助。下面是我的屏幕世界代码。

public void  Shoot ()
{
    //bullet_target
    var layerMask = (1 << 8);
    layerMask = ~layerMask;
    Vector3 bullet_target = Vector3.zero;
    Ray ray = Camera.main.ScreenPointToRay( new Vector3(screen_width_mid, screen_height_mid, 0) );
    RaycastHit hit;
    GameObject hit_game_object;
    Transform hit_transform;
    if (Physics.Raycast (ray.origin, ray.direction * 1000 ,out hit, 1500.0f , layerMask) ) 
        {
            bullet_target = hit.point;
            hit_game_object = hit.transform.gameObject;
            hit_transform = hit.transform;
        }else
        {
            hit_game_object = null; 
        }
        if(hit_game_object!=null)
            {               
                if( hit_game_object.tag=="head" )
                    {
                        //blah blah do any stuf
                    }
            }
        }
}

1 个答案:

答案 0 :(得分:1)

如果你想在屏幕空间中获得对象的位置,只需使用Camera.WorldToScreenPoint();

我假设你已经有了一个跟随你的鼠标的十字准线游戏对象,可能会被你的弓箭手限制到一定距离。

https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

Transform crosshair;

Vector3 GetCrosshairScreenPos()
{
    if(crosshair)
    {
        Vector3 worldPos = crosshair.position;
        Vector3 screenPos = Camera.main.WorldToScreenPoint(crosshair.position);
        return screenPos;
    }
}