- Home /
Rays not hitting (most of the time)
So i'm making a first person shooter and im using this code to shoot a ray:
ray = GameObject.FindGameObjectWithTag("MainCamera").camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0))
if (Physics.Raycast(ray, out hit, 1000.0f))
Sometimes this works, but most of the time the hit never registers with the enemy.
here is a picture showing where the rays are being shot and also showing the box collider for the enemy.
http://i.imgur.com/aJJKvGz.png When I print to the console what I have hit, its just saying that I hit the terrain, or something else that is behind the enemy.
Based on your screenshot and console output (lack of), sounds like your 'box collider' is not getting hit maybe because of its tag, physics layer, etc, so the ray is shooting through
I'm using Debug.Drawray to see where its going, and its going straight through the enemies box collider.
I spawn 10 enemies from the same prefab and some of them NEVER can get hit.
I stop the program and start again and the ones I couldn't hit before are now detecting hits and others wont be able to get hit.
I really have no idea whats wrong, im pretty sure its something wrong with unity...
What layer is your box collider on? Look at Edit / Project Settings / Physics - does that layer interact with the layer shooting the Ray? Show the code for your actual raycast "hit" logic?
Is there a pattern? Such as it always hits the first one created, or it only hits instances that were in the scene already, etc? Can you please post more of your raycast code above, specifically after the if statement?
Here are the settings you're talking about.
http://i.imgur.com/Lfl$$anonymous$$oDP.png
Everything is on the default layer.
I found that moving to a different location can sometimes stop the ray from passing through the enemy without triggering a hit, still no idea what is causing this though, because I can kill other enemies at that location and others I cant.
Here is all the code for my raycasting
ray = GameObject.FindGameObjectWithTag("$$anonymous$$ainCamera").camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
if (Physics.Raycast(ray, out hit))
{
Debug.Log("Hit: " + hit.transform.name + ".\n");
if(hit.transform.tag=="Enemy")
{
hit.transform.Send$$anonymous$$essage("Hit");
}
Debug.DrawLine(transform.position, hit.point, Color.red, 200);
}
Your answer
Follow this Question
Related Questions
Raycasting ignoring small sized object 1 Answer
Getting the Furthest Point on a Ray 1 Answer
AI Pathfinding using RayCast 0 Answers
For each Raycast? 1 Answer
Setting a point with a ray C# 1 Answer