- Home /
convert world to screen (crosshair follow)
hi! help with converting in screen coords. I made crosshair following where is muzzle of tank aims. But i can't convert world coord in screen rightly.
if(Physics.Raycast(firePoint.position, firePoint.TransformDirection(Vector3.left), out hit))
{
Debug.DrawLine(firePoint.position,hit.point,Color.red);
// Vector 3 of hit.gameobject
pointCursor = Camera.main.WorldToScreenPoint(hit.transform.position);
}
void OnGUI()
{
Vector2 vector2 = GUIUtility.ScreenToGUIPoint(new Vector2(pointCursor.x, pointCursor.y));
Rect labelRect = new Rect();
labelRect.x = vector2.x;
labelRect.y = vector2.y;
labelRect.width = cursorTexture.width;
labelRect.height = cursorTexture.height;
GUI.DrawTexture(labelRect,cursorTexture);
}
Answer by aldonaletto · Aug 09, 2012 at 11:16 AM
You should use hit.point: this returns the 3D point where your raycast hit something. If you use hit.transform.position, the crosshair will be located at the hit object's pivot: looks weird for small objects, and completely wrong for the bigger ones.
... if (Physics.Raycast(firePoint.position, firePoint.TransformDirection(Vector3.left), out hit)){ // Use the hit point instead: pointCursor = Camera.main.WorldToScreenPoint(hit.point); } ...NOTE: The crosshair will be rendered even if the raycast doesn't hit anything, what may seem weird. You can avoid this using a boolean variable like this:
private var hitSomething: boolean; // <- declare this variable
... // assign the raycast result to it: hitSomething = Physics.Raycast(firePoint.position, firePoint.TransformDirection(Vector3.left), out hit); if (hitSomething){ // Use the hit point: pointCursor = Camera.main.WorldToScreenPoint(hit.point); } ...
function OnGUI(){ if (hitSomething){ // only draw the crosshair if something hit: Vector2 vector2 = GUIUtility.ScreenToGUIPoint(new Vector2(pointCursor.x, pointCursor.y)); ... GUI.DrawTexture(labelRect,cursorTexture); } }
Your answer
![](https://koobas.hobune.stream/wayback/20220613075421im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Crosshair disappears? 2 Answers
first person crosshair 3 Answers
FPS Tutorial problem 1 Answer
Make crosshairs disappear while aiming 0 Answers
Snapping Issue 2 Answers