script attached to main camera wont shoot debug line straight. also wont detect collision on raycast
I have a main camera object with a script attached. I have a child object of the camera, the "crosshairs". which is a transparent cube with a crosshairs image attached. It basically follows the camera and allows the user to direct the raycast to aim at some 3d cubes.
I am also drawing a debug line in the same direction as the raycast to see where iam aiming it. my script is below.
public float maxdist = 100f;
public Ray ray;
void Update () {
ray = new Ray(gameObject.transform.position, gameObject.transform.forward * maxdist);
RaycastHit hit;
Debug.DrawLine(gameObject.transform.position, gameObject.transform.forward * maxdist, Color.green);
if (Physics.Raycast(ray, out hit, maxdist))
{
if (hit.collider.tag == "box")
{
hit.transform.SendMessageUpwards("setRunning", true);
Debug.Log("box hit!!!!");
}
}
}
}
first, the debug line itself doesnt intersect the center of the crosshairs. so it seems the aim of the crosshairs will be slightly off. I am not sure why. If i add "new Vector3(0,0,1)" instead of Vector3forward. the debugline shoots straight initially but obviously doesnt update. I thought max dist might be the issue here but i removed it and z was even further away from the crosshairs. Also ive tagged my boxes with "box". when i try to pass the raycast through these boxes the "hit" returns "untagged" this is also confusing me. Any help would be really appreciated!
ive also tried grabbing the camera object in this script (which is attached to the camera). But, the camera object is always null? i used gameObject.GetComponent(); in the Start() method. I am having no luck with this. iam a relatively experinced programmeer but new to unity so I am still learning.
Answer by LarryTheBrave · Jun 04, 2019 at 04:29 AM
The one fishy thing I see so far is looking for the tag on the collider rather than the GameObject. Not sure if there is even such a thing as a collider tag. Alternately try using a built-in tag or even the name instead to find the object, or public GameObject linked to the box itself i.e. public GameObject theBox, then check collider == theBox.
Your answer
Follow this Question
Related Questions
Raycast Not Detecting Hit 0 Answers
RayCast appears to bug out for no apparent reason 1 Answer
Raycast help 0 Answers
Raycast is going through collider (A plane) 0 Answers
Switching from object to object with Raycast Problem 1 Answer