- Home /
Raycast from camera not hitting Terrain
So, I have this.
private void getInputData()
{
//gets the mouse click position and places a unit at that location.
RaycastHit hit;
Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray ,out hit, 1000))
{
Debug.Log(hit.point);
if (hit.collider.gameObject.tag == "Terrain")
{
//Creates a unit if nothing is there.
Debug.Log("I hit the terrain!");
createSelectedUnit (selectedUnit, hit.point);
}
else if (hit.collider.gameObject.tag == "Melee" ||
hit.collider.gameObject.tag == "PlayerHero")
{
//This is a blanket if/then statement for all units that the player can control.
//If player hits the unit, show some info on GUI.
}
else if (hit.collider.gameObject.tag == "Dist_Melee" ||
hit.collider.gameObject.tag == "EnemyHero")
{
//This is a blanket if/then statement for all units that the enemy controls.
//If player hits the unit, show some info on GUI.
}
}
}
So I'm shooting a ray from a camera at a terrain at (value, 0, value) and according to the hit.point debug it's not hitting the ground half the time. That is, it's not (value, 0, value) being shown but (value, value, value).
My question is this: What do I do to ensure that the ray being shot from the camera will always hit the ground?
Bonus points if you can shed some light on why the ray from the camera isn't hitting the ground to begin with.
Problem solved. Cause was between chair and keyboard. I added a collision node that was overly large and it was messing with the raycast.
Answer by robertbu · Nov 12, 2014 at 05:04 AM
First, debug it. On line 8, put:
Debug.Log(hit.collider.name + ", " + hit.collider.tag);
This will tell you what (if) you are hitting. Second, if you only want to detect the terrain, then use Collider.Raycast() rather than Physics.Raycast():
if ( Terrain.activeTerrain.collider.Raycast(ray, out hit, 1000f) )
So apparently I made a huge collision node on the player cylinder and totally forgot about it. ._. Deleting it solved every problem in the history of mankind. Woo!
Your answer
Follow this Question
Related Questions
Is it possible to check how much a trigger is filled by %? 1 Answer
c# How do I set up continuous raycast collision detection? 1 Answer
Raycast Mouse Click On Specific Objects Only 0 Answers
Creating 2d image map of objects based off 3d space colliders Unity C# 0 Answers
Multiple Cars not working 1 Answer