简体   繁体   中英

how to racast 3d world to screen (unity3d)

In my shoot method, I am getting raycast by exact mid of screen, working fine, but now for more appropriate I want to change it in world to screen (and also between cross hair, not from mid of screen). but I didn't get any directions. Thanks in advance for helping. below is my code for screen to world.

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

If you want to get object's position in screen space just use Camera.WorldToScreenPoint();

I'm assuming that you already have a crosshair gameobject that's following your mouse and might be constrained to some distance from your archer.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM