Intro
In game world theres a capsule player marked with layer !playerBody to be ignorred by ray.
Debug.DrawRay(); shows the rays correctly.
Rays are shot from a middle point down and out; forming a cone shape w/ a slight lip underneath player.
Goal
A dynamic amount of rays will test for ‘isGrounded’ on ‘playerBody’:
isGrounded == true : On the ground
isGrounded == false : Air borne
Pseudo code
(Player on slope)
-
Ray1:False → Next, Ray2:False → Next, Ray3:True → BoolTrue (Start over)
-
Ray1-16:False → BoolFalse (Start over)
Problem
Raycast allways returns false.
NOTE
Camera and playerCapsule(rigidBody, constrainedRotation) movement is excluded from example script.
_
public class X: MonoBehaviour
{
public bool isGrounded = false;
public int rayAmount = 20; //Amount of rays cast
public float rayOffset = -3f;
public float rayRadius = 0.35f;
public LayerMask groundingRayLayerMasking; //Layers to ignore: !playerBody
void FixedUpdate ()
{
Vector3 playerPos = transform.position;
int j = 0; //Do not delete!
for (int i = 1; i < rayAmount; i++)
{
RaycastHit tempHit = new RaycastHit();
if (j > (rayAmount - 1)) // (rayAmount(16)-1)::(since 0 incl. and '0' is required for calc. of 'angle')
{
j = 0;
}
float angle = j * Mathf.PI * 2 / rayAmount;
Vector3 pos = new Vector3(Mathf.Cos(angle), rayOffset, Mathf.Sin(angle)) * rayRadius;
//float temp_rayDistance = Vector3.Distance(playerPos, pos); //TEMP
Debug.DrawRay(playerPos, pos, Color.blue, Time.deltaTime, false);
//Debug.Log(temp_rayDistance); //TMEP
if (Physics.Raycast(playerPos, (pos + playerPos), out tempHit, 5.2f, groundingRayLayerMasking))
{
//Debug.Log("groundRay hit");
isGrounded = true;
i = 0; //Restart squence from 0
j = 0; //Restart squence from 0
//break;
}
else
{
//Debug.Log("No groundRay hit");
isGrounded = false;
if (i > (rayAmount - 1))//Restart sequence reaching end!
{
i = 0;
}
}
j++;
}
}
}