Hi there. I’m looking to create a physics system for my characters so that they can be affected by gravity without falling through terrain. However, I’m having some trouble getting my raycasts to actually detect the colliders I need them to detect (the terrain). Here is my code:
if (velocity.y < 0)
{
// setting up variables to detect for terrain in a circular series of raycasts beneath the player.
float angle = 0;
float magnitude = 0;
List<Vector3> hitPoints = new List<Vector3>();
while (angle < 360)
{
// determine the starting point
Vector3 startPoint = transform.TransformDirection(new Vector3(Mathf.Cos(angle * Mathf.Deg2Rad), 0, Mathf.Sin(angle * Mathf.Deg2Rad)) * magnitude);
// cast a ray from the starting point going downward
RaycastHit[] rayCastHits = Physics.RaycastAll(startPoint, Vector3.up * velocity.y, Mathf.Abs(velocity.y));
// loop through the hits
foreach (RaycastHit hit in rayCastHits)
if (hit.collider.tag == "Terrain")
// add the position of the hit to a list to be looped through later
hitPoints.Add(hit.point);
// increment the magnitude and angle variables
if (magnitude == 0)
magnitude = 1;
else
angle += 60f;
}
// if the raycasts returned any hits
if (hitPoints.Count > 0)
{
// determine the highest y value of all the collisions detected
float moveToY = hitPoints[0].y;
foreach (Vector3 point in hitPoints)
if (point.y > moveToY)
moveToY = point.y;
// move to the point of the collision and reset the y velocity to zero
transform.position = new Vector3(transform.position.x, moveToY, transform.position.z);
velocity.y = 0;
}
}
My terrain object has a collider attached and is tagged as “Terrain”, yet when I run this code, I don’t get any collisions for my terrain. I think i may be implementing Physics.RaycastAll()
incorrectly. Is the direction
argument relative to origin
, or are they both in world coordinates? Or is there another problem with my code?