I’m having an issue with my raycast not matching up with the cross hair (technically a dot). The cross hair appears to be in the centre of the screen, but the hit markers from the raycast appear below the cross hair.
Is there a reason Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f) doesn’t work? I assume those values relate to the centre of the screen, where the cross hair is?
This is what i believe you are looking for
if (Physics.Raycast(crosshairPosition, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
How i setup up a simple cross hair with scale and selection.
Things to do:
Cross-hairs (i just created one of every basic unity sprite)
Drag all new sprites (cross-hairs )under the main camera
Set all sprite positions to X = 0, Y=0, Z =0.1
Set all sprite Scales to X = 0.01 , Y=0.01, Z =0
Set the Main Camera Clipping Planes to 0.01
Add basic Script from below to the Main Camera
This is the way i do cross hairs im no pro but it works
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrosshairBasic : MonoBehaviour
{
public Color colorCrosshair;
public Vector3 crosshairPosition;
[Range(0.001f, 0.01f)]
public float crossHairScale = 0.005f;
[Range(1, 5)]
public int crosshairSelection;
public GameObject crosshairImage;
public Transform ItemHolder;
public Transform crossHairHolder;
public bool debugLine = false;
public LineRenderer lineRenderer;
GameObject obj;
// change to a start function this it so OndrawGizmos to test in editor
void OndrawGizmos()
{
crosshairPosition = transform.position;
foreach (Transform child in crossHairHolder)
{
child.gameObject.SetActive(false);
}
crosshairImage = crossHairHolder.GetChild(crosshairSelection).gameObject;
crosshairImage.SetActive(true);
crosshairImage.transform.localScale = new Vector2(crossHairScale, crossHairScale);
crosshairImage.GetComponent<SpriteRenderer>().color = colorCrosshair;
}
public RaycastHit FireRay()
{
RaycastHit hit;
if (Physics.Raycast(crosshairPosition, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
{
obj = hit.collider.gameObject;
if (debugLine)
{
DebugRay(crosshairPosition, hit.point);
}
}
return hit;
}
void DebugRay(Vector3 start, Vector3 end)
{
lineRenderer.SetPosition(0, start);
lineRenderer.SetPosition(1, end);
}
}
Hey, thanks for replying. I’m more trying to understand why Camera.main.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0f)) doesn’t work for me, though. Any idea why it isn’t finding the centre of the screen? Apologies, but I get a little obsessed with minute details until I understand them.