Reputation: 509
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
}
}
}
}
Upvotes: 0
Views: 168
Reputation: 1256
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;
}
}
Upvotes: 1