How do I make my crosshair more accurate?

So basically I have a gun and i’m using raycasting to shoot. When i’m close to my target it goes fine, but when I go really far, it never hits the target. This is my current script for shooting:

public void CastRay()
	{
		RaycastHit Hit;
	
		if(Physics.Raycast(transform.position,transform.forward,out Hit,Power))
		{
			if(Hit.transform.gameObject.tag == "target")
			{
               Destroy(Hit.transform.gameObject);
			}
		}
	}

And this is what i’m using for the crosshair

myRay = new Ray(transform.position,transform.forward);
CrossHairPosition = Camera.main.WorldToScreenPoint(myRay.GetPoint(Power));
		
GUI.Label(new Rect(CrossHairPosition.x - (CrossHair.width / 2),CrossHairPosition.y - (CrossHair.height / 2),CrossHair.width,CrossHair.height),CrossHair); //Crosshair is 2D texture

What’s wrong with this code ? When i go very far, it’s not shooting in the crosshair anymore. Infact, it doesn’t come even close to shooting in the crosshair.

I presume this is a FPS … if so is your weapon (Gun) slightly off centre of the view, if it is and you are firing the ray cast from there you will never hit the target until you are close as it’s not casting to the centre of the screen (where again I presume you have your crosshair) what I do is cast the ray from the centre of the camera so then it goes straight through the crosshair -

var ray : Ray = Camera.main.ViewportPointToRay (Vector3(0.5,0.5,0));

    if (Physics.Raycast (ray, hit, 1000)){

        if(Hit.transform.gameObject.tag == "target"){
               Destroy(Hit.transform.gameObject);
         }
    }

Hope this helps …

I should have spotted it the first time. You are using GUI coordinates to display the crosshair, but you are calculating screen coordinates. You can convert between the two by:

CrossHairPosition.y = Screen.height - CrossHairPosition.y;

The bottom-left of the screen is (0,0) with screen coordinates. The top-left of the screen is (0,0) for GUI coordiantes.