- Home /
Raycast to middle screen doesn't work
Hi, I have this code:
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(x, y));
RaycastHit hit = new RaycastHit();
Physics.Raycast(ray, out hit);
if (hit.collider.tag == "Player")
{
SomeFunction();
}
The problem is that the if statement is never true, I have a crosshair (GUITexture) drawed in the middle of the screen, when I focus it on a player and I shoot it's like that I don't shoot to the player.
Any suggestions?
Marco
Answer by aldonaletto · Jan 02, 2012 at 01:50 PM
You should use an if to avoid null reference errors, and there's no need for the new RaycastHit instruction, but the code seems ok.
It's easier to use ViewportPointToRay to create a ray from the middle of the screen - just pass Vector3(0.5f, 0.5f, 0). Try something like the code below - it includes a debug instruction to show the hit object's name, if any:
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); RaycastHit hit;
if (Physics.Raycast(ray, out hit)){ print("Hit "+hit.collider.name); if (hit.collider.tag == "Player"){ SomeFunction(); } }
It says every time Hit Terrain, that's like that it don't recognize the player, but it has the tag Player attached, there is a way to draw the ray so I can view it?
@Statement I think that this only work in 2D games, I should you a Line Render, but I don't know how.
Use Debug.DrawRay right after the print:
print("Hit "+hit.collider.name);
Debug.DrawRay(ray.position, 100 * ray.direction, Color.red);
...
The ray starts at the camera position, thus in the Game view you only see a $$anonymous$$uscule red dot at the center of the screen - and only if you click the Gizmos button on the top of the Game view. An alternative is to select Windows/Layout/2 by 3, what lets the Game and Scene views side by side, thus you can see the ray in the Scene view.
@marf: Just fyi: Debug.DrawLine /.DrawRay only works in the editor for debug purposes. If you build your game those lines aren't visible. The type of game is irrelevant since Unity is always a 3D-engine, even when you just use 2 dimensions.
$$anonymous$$ake sure your player have any kind of collider (BoxCollider, CapsuleCollider, SphereCollider or a CharacterController which is also a collider!) attached. If the collider is attached to a child object make sure the child has also the "Player" tag.
Your answer
Follow this Question
Related Questions
Raycasting Accurately with gun 2 Answers
How to make constant click position ? 0 Answers
Not getting right value; ScreenPointToRay 0 Answers
Raycast hits everything on the screen 2 Answers
raycast screenpointtoray isnt working for some reason 0 Answers