- Home /
How to check if a raycasthit detects an angle less than 45 degrees and touches the ground
I have this script:
void IsGrounded()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, Vector3.down, out hitInfo))
{
if (hitInfo.normal.y > notSlopes)
isgrounded = true;
}
else isgrounded = false;
}
Where notslopes stands for slopes that are not bigger than 45 degrees and to check if collision with the floor to restrict gravity when the character climbs on slopes.
How can I fix this, cause it is not working.
Answer by Kavorka · Apr 02, 2014 at 01:18 AM
Change row 7 to:
if (hitInfo.normal.y < .707f)
then isgrounded will be true if you are standing on a slope steeper than 45 degrees.
[CODE] void IsGrounded() {
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, Vector3.down, out hitInfo))
{
if (hitInfo.normal.y < .707f)
angleLT45 = true;
else
angleLT45 = false;
if (hitInfo.distance > 1f) // Change 1f to what you need
isgrounded = false;
else
isgrounded = true;
}
} [/CODE]
Answer by JuanseCoello · Apr 02, 2014 at 02:06 AM
It doesnt work, doesnt detect collision with the ground when applied gravity. here is my code:
using UnityEngine; using System.Collections;
public class TP_Controller : MonoBehaviour
{
public static Rigidbody Rigidbody2;
public static TP_Controller Instance;
RaycastHit hit;
float dist;
Vector3 dir;
public bool isgrounded;
public bool angleLT45;
void Awake () // Debe quedarse en awake
{
Rigidbody2 = GetComponent("Rigidbody") as Rigidbody;
Instance = this;
}
void Update ()
{
if (Camera.mainCamera == null)
return;
GetLocomotionInput();
TP_Motor.Instance.UpdateMotor();
dist = 10;
dir = new Vector3(0,-1,0);
Debug.DrawRay(transform.position, dir * dist, Color.green);
}
void IsGrounded()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, Vector3.down, out hitInfo))
{
if (hitInfo.normal.y < .707f)
angleLT45 = true;
else
angleLT45 = false;
if (hitInfo.distance > .1f) // Change .1f to what you need
isgrounded = false;
else
isgrounded = true;
}
}
AND THEN THERE IS THIS CODE ON ANOTHER SCRIPT
void ApplyGravity()
{
if (TP_Controller.Instance.isgrounded == true)
return;
if (MoveVector.y > -TerminalVelocity)
MoveVector = new Vector3(MoveVector.x, MoveVector.y - Gravity * Time.deltaTime, MoveVector.z);
if ((TP_Controller.Instance.isgrounded == false) && MoveVector.y < -1)
MoveVector = new Vector3(MoveVector.x, -1, MoveVector.z);
}
$$anonymous$$aybe it doesnt check for anything to collide. It goes through.
What I want is that the raycast casts a ray of 1f, but when it collides to the floor it checks is grounded = true. That is it, maybe I didnt asked well the question.