Solved. As suggested to me in a reply (thanks), I have offset the origin of the ray by 0.5 so it would not be at the origin of the camera.
Hello, I am trying to use Raycast to change the color of a crosshair when the player looks at an object tagged “interactable,” and I successfully did but with a big issue. When aiming the player (and ultimately the ray) toward an object tagged “interactable” and has colliders, the crosshair only turns green when looking at certain spots on the object. I believe the ray may be only getting info from the endpoint instead of anything between the ray and the endpoint, but I do not know why. How can I fix this?
My scripts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayViewer : MonoBehaviour {
public float range = 50f;
private Camera fpsCam;
void Start()
{
fpsCam = GetComponent<Camera>();
}
// Update is called once per frame
void Update ()
{
Vector3 lineOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
Debug.DrawRay(lineOrigin, fpsCam.transform.forward * range, Color.green);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrosshairSwap : MonoBehaviour
{
public GameObject activeCrosshair;
public GameObject inactiveCrosshair;
public Camera fpsCam;
public float range = 2f;
private LineRenderer laserLine;
void Start()
{
//laserLine = GetComponent<LineRenderer>();
}
void Update()
{
Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
//laserLine.SetPosition(0, rayOrigin);
if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out hit, range) && hit.transform.tag == "Interactable")
{
// laserLine.SetPosition(1, hit.point);
activeCrosshair.SetActive(false);
inactiveCrosshair.SetActive(true);
}
else
{
// laserLine.SetPosition(1, rayOrigin + (fpsCam.transform.forward * range));
activeCrosshair.SetActive(true);
inactiveCrosshair.SetActive(false);
}
}
}