Home > database >  Trying to get a variable changed on Collision
Trying to get a variable changed on Collision

Time:02-22

I'm trying to make flappy bird and I'm trying to make it when the bird hits the "floor" a variable changes and then the script for the movement is not able to go. Kinda hard for me to explain but here is the code i have:

    void Update()
{
    void OnCollisionEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "floor") // || col.gameObject.tag == "Pipe")
        {
            active = 0;
        }
    }

    if (active == 1)
        if (Input.GetKeyDown("space"))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector3(0, 10, 0);
        }
 
}

That is my code ^ Please help : )

CodePudding user response:

void Update()
{
   if (active == 1)
   {
       if (Input.GetKeyDown("space"))
       {
            GetComponent<Rigidbody2D>().velocity = new Vector3(0, 10, 0);
       }
   }
}

void OnCollisionEnter2D(Collider2D col)
   {
      if (col.gameObject.tag == "floor") // || col.gameObject.tag == "Pipe")
   {
      active = 0;
   }
}

This code works fine for me, make sure you add Rigidbody2d to the player add the box collider and the tag to the floor

CodePudding user response:

First of all you have the OnCollisionEnter2D nested under Update as a local function. Unity doesn't find and call it this way, it needs to be at class level.

And then you set

active = 0;

but check for

active == 1

this seems odd. I would expect you check for the same value.

In general rather use a bool flag:

private bool active;

// reference via the Inspector if possible
[SerializeField] private Rigidbody2D _rigidbody;

private void Awake()
{
   // as fallback get it ONCE on runtime
   if(!_rigidbody) _rigidbody = GetComponent<Rigidbody2D>();
}

private void Update()
{
   if (active)
   {
       if (Input.GetKeyDown("space"))
       {
            // only change the Y velocity, keep the rest
            // that's needed e.g. if you are moving sideways currently
            _rigidbody.velocity = new Vector3(_rigidbody.velocity.x, 10);
            // immediately disable jumping
            active = false;
       }
   }
}

private void OnCollisionEnter2D(Collider2D col)
{
    if (col.gameObject.CompareTag("floor") || col.gameObject.CompareTag("Pipe"))
    {
        active = true;
    }
}

// also disable jumping when exiting just in case
void OnCollisionExit2D(Collider2D col)
{
    if (col.gameObject.CompareTag("floor") || col.gameObject.CompareTag("Pipe"))
    {
        active = false;
    }
}
  • Related