- Home /
The question is answered, right answer was accepted
Help with layermask and raycast!!! HELP
I am trying to set a mask, the numeber 8 one, and I have put an object there, the floor, so when the raycast collides with it detects the floor. But I dont know what happens, it doesnt recognize the floor object. The ray works perfectly by the way, that is not the problem.
Here is the code:
GameObject Piso = GameObject.Find("Floor"); // this is the gameobject floor
int layerMask = 1 << 8; // this variables go at the begining
void IsGrounded() // this is my function that casts the raycast
{
RaycastHit hitInfo;
if (Physics.Raycast(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, out hitInfo, Mathf.Infinity, layerMask))
{
if (hitInfo.distance > 0.1f) // Change .1f to what you need
Debug.DrawRay(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, Color.blue);
isgrounded = true;
}
if (hitInfo.distance < 0.5f){
Debug.DrawRay(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, Color.red);
isgrounded = false;
}
}
Am I missing something? By the way, I placed the object Floor in the scene in the layer number 8, but somehow it doesnt recognize the raycast. HEEELP!!!
By the way, the raycast is casted from a rigidbody called rb inside the player.
Answer by meat5000 · Apr 12, 2015 at 03:40 PM
Use
LayerMask layerMask = 1 << 8;
instead of
int layerMask = 1 << 8;
Answer by hbalint1 · Apr 12, 2015 at 02:58 PM
Is it possible, that you used the braces wrong? I think you are missing one '{' in the 12th row:
if (hitInfo.distance > 0.1f) {
if the distance is < 0.5f the grounded will always be false, because it looks like this:
void IsGrounded()
{
...
if (Physics.Raycast..)
{
if (hitInfo..) // I think here you are missing a '{', because the other if is out of the Raycast's if
}
if (hitInfo.distance < 0.5f){ // this will always be executed, so as I said above: if the distance less, than 0.5f, the isGrounded will always be false
...
}
}
I hope it's understandable. So:
void IsGrounded() // this is my function that casts the raycast
{
RaycastHit hitInfo;
if (Physics.Raycast(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, out hitInfo, Mathf.Infinity, layerMask))
{
if (hitInfo.distance > 0.1f)
{ // Change .1f to what you need
Debug.DrawRay(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, Color.blue);
isgrounded = true;
}
if (hitInfo.distance < 0.5f)
{
Debug.DrawRay(rb.transform.position + Vector3.down * 3f, Vector3.up * 5f, Color.red);
isgrounded = false;
}
}
}