0
votes

I am trying to learn the unity 2d systems from PushyPixels I am on episode 2, and I am trying to set a bool to false when not touching the ground. It will not set itself to false, unless I use grounded = false;. I am trying everything. I know the game objects are in the array, and I know they are not touching the ground when I am falling off a platform. What's wrong?

using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {

public string jumpButton = "Fire1";
public float jumpPower = 10.0f;
public Animator anim;
public float minJumpDelay = 0.05f;
public Transform[] groundChecks;
public float jumpTime = 0.0f;
public bool grounded;
// Use this for initialization
void Start () 
{
    anim = gameObject.GetComponent<Animator>();
    grounded = true;
}

// Update is called once per frame
void Update () 
{

    foreach(Transform groundCheck in groundChecks)
    {
        grounded = grounded | Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
    }
    anim.SetBool("Grounded", grounded);
    if(jumpTime > 0) {
        jumpTime -= Time.deltaTime;
    }
    if(Input.GetButtonDown(jumpButton) && anim.GetBool("Grounded")) 
    {
        anim.SetBool("Jump", true);
        grounded = false;
        rigidbody2D.AddForce(transform.up * jumpPower);
        jumpTime = minJumpDelay;
    }
    if(anim.GetBool("Grounded") && jumpTime <= 0)
    {
        anim.SetBool("Jump", false);
    }
}

}

2
You have grounded = grounded | .... Shouldn't that be a logical or ||? Keep in mind that with a logical or, when grounded starts with true it will never become false on that line. But it's just a remark. I am not sure that it is your problem. - Silvermind
Thank you for your response. I have tried the logical or, and that didn't work. That is what Pushy Pixels use, but from my experience with coding the x= x | y should work. The logical or works for them... - jmaster2013

2 Answers

1
votes

In your Update routine before your foreach loop you have to set grounded = false. That way you assume that you are in the air unless at least one of those ground checks tells you otherwise.

0
votes

You probably got this fixed already, but if not, use:

   public float GroundRadius = 0.1f;//change as needed until done testing then remove public
   public LayerMask WahtIsGround;//you can set the ground layermask from the inspector this way or make it private and set it on awake.

public transform GroundCheck; I would set this on awake as well but here you can drop it in and go.

Also, put things with physics in FixedUpdate()

   void FixedUpdate()
   {
          Grounded = Physics2D.OverlapCircle (GroundCheck.position, GroundRadius, WhatIsGround1);
   }