So I’ve been using an isGrounded variable to limit jumping to only when on the ground, but if the player walks off of a platform, then they can jump in the air. I did some research and it seemed like people used a raycast to check whether or not the player was grounded. I’ve never used a raycast before so this is my first attempt and unity shows nothing as wrong in the script, but I can’t move when I play the scene. I assume that’s because my if statement is never true, but I don’t know how to fix this as I used the unity scripting API as my example. I want it so the raycast is constantly happening and isGrounded is set to true only when the raycast hits the floor below the player. Please let me know what you think I should change to make this work, any input is welcome. Thank you!
void Start () {
distToGround = collider.bounds.extents.y;
}
bool IsGrounded()
{
return Physics.Raycast(transform.position, - Vector3.up, distToGround + 0.1f);
}
public void NoMove()
{
movement=false;
}
void FixedUpdate ()
{
if (IsGrounded())
{
speedH=30;
}
if (!IsGrounded())
{
speedH=3;
}
}
void Update ()
{
if (movement)
{
if (Input.GetKey (KeyCode.RightArrow))
{
animation.Play ("Allosaurus_Walk");
rigidbody.AddForce(Vector3.right *speedH);
}
if (Input.GetKeyUp (KeyCode.RightArrow))
{
animation.Stop ("Allosaurus_Walk");
animation.Play ("Allosaurus_Idle");
}
if (Input.GetKeyUp (KeyCode.LeftArrow))
{
animation.Stop ("Allosaurus_Walk");
animation.Play ("Allosaurus_Idle");
if (Input.GetKeyUp (KeyCode.LeftArrow))
{
transform.Rotate (0,180,0);
}
}
if (Input.GetKey (KeyCode.LeftArrow))
{
animation.Play ("Allosaurus_Walk");
rigidbody.AddForce(Vector3.left *speedH);
if (Input.GetKeyDown (KeyCode.LeftArrow))
{
transform.Rotate (0,180,0);
}
}
if (moveUp && IsGrounded())
{
animation.Play ("Allosaurus_JumpRight");
rigidbody.AddForce(Vector3.up * speedZ);
}
if (Input.GetKey ("d"))
{
animation.Play ("Allosaurus_Run");
rigidbody.AddForce(Vector3.right *speedH);
}
if (Input.GetKeyUp ("d"))
{
animation.Stop ("Allosaurus_Run");
animation.Play ("Allosaurus_Idle");
}
if (Input.GetKeyUp ("a"))
{
animation.Stop ("Allosaurus_Run");
animation.Play ("Allosaurus_Idle");
if (Input.GetKeyUp ("a"))
{
transform.Rotate (0,180,0);
}
}
if (Input.GetKey ("a"))
{
animation.Play ("Allosaurus_Run");
rigidbody.AddForce(Vector3.left *speedH);
if (Input.GetKeyDown ("a"))
{
transform.Rotate (0,180,0);
}
}