- Home /
Only able to jump when grounded.,Only doing something if something is true
IsGrounded.cs { public bool grounded = false;
void OnCollisionEnter2D (Collision2D collisionGround)
{
if (collisionGround.collider.tag == "Ground")
{
grounded = true;
} else
{
grounded = false;
}
}
Movement.cs
void FixedUpdate() { if (grounded == true) { if(Input.GetKey("Space")) { rb.AddForce(new Vector2(0, jumpSpeed * Time.deltaTime), ForceMode2D.Impulse); }
Answer by MooGaming227 · Oct 13, 2018 at 10:11 PM
How I usually do it in my games:
public bool CheckGroundProximity() { isGrounded = false;
Ray ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, 0.25f, LayerMask.GetMask("Terrain", "Walkable"))){
isGrounded = true;
}
return isGrounded;
}
Raycasts a certain distance down from your players position and if it hits a ground collider on the layer "Terrain" or Walkable then return true. In your if it should be:
if (CheckGroundProximity() == true) { Code Here }
Didn't work. On CheckGroundProximity it says ''Not all code paths return a value'' And on return it says since 'RayCast.Update returns void a return keyword must not be followed by an expression. I don't get it.
Declare the isGrounded Boolean in your script as a public bool somewhere or inside the function if you don't want it to be accessed anywhere else. Ex:
public bool isGrounded;//AT TOP OF SCRIPT
or
public bool CheckGroundProximity() { bool isGrounded = false; Ray ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, 0.25f, Layer$$anonymous$$ask.Get$$anonymous$$ask("Terrain", "Walkable"))){
isGrounded = true;
}
return isGrounded;
}