Allowing input only when collision is true?

So I want to be able to spawn/drop an item at a specific location only if my player is standing in a specific location.
I have been able to set up the ability to drop the item no matter where my player is at but I am unable to figure out how to drop it if my player is standing in a specific spot.

I assume this is because I can only check for keyboard input in the Update (or similar Method) and I can only check for collision in the OnTriggerEvent2d(Collider2d other) method.

Here is the code I am using to check for collision so I can pickup items and the code that I am using to drop the item:

    //Picking up Items
    void OnTriggerEnter2D(Collider2D other)
    {
        //Insures that you can only pickup 1 set of dishes at a time
        if (other.gameObject.CompareTag("DirtyPlates") && !inventory.Contains("Dirty Plates"))
        {
            inventory.Add("Dirty Plates");

            Destroy(other.gameObject);
        }

        //Collision Test
        //This code works
        if (other.gameObject.CompareTag("Collider") && inventory.Contains("Dirty Plates"))
        {
            Debug.Log("Collision Working");
        }
         
    }

//Dropping Items
//This is the code that isn't really working
if (other.gameObject.CompareTag("Collider") && Input.GetKeyDown(KeyCode.Keypad0) && inventory.Contains("Dirty Plates"))
        {
            //Spawn Dirty Plates Sprit infront of players location
            Instantiate(dirtyPlates, spawnPosition.position, transform.rotation);

            //And remove it from the list
            inventory.Remove("Dirty Plates");
        }

Thanks,

  • Patrick

Set a “flag” (typically a boolean variable) when your player is in the right spot (OnTriggerEnter2D) and clear it when they leave that location (OnTriggerExit2D).

bool canDropDishes = false;   // initialize false or true

Then when you want to drop the dishes, check that variable to see if it’s allowed.

Jay

That worked! Thanks a lot. I thought I might have to do something like that because I had done something similar with a text game I made for my programming class last fall. But was unsure about how I would do it in Unity.

Thanks again.

  • Patrick
1 Like

Alternately, you can always use the IsTouching calls to detect if stuff is in contact. This means you don’t need to hook into the callbacks and the call is super-fast to call as it doesn’t actually work out collisions, it just looks if there’s an existing contact.

Note that just like the callbacks, the contacts are only updated during the fixed-update when the physics system updates.

Thanks for the advice Melv. I am only working on the prototype right now but the IsTouching method does sound like it may make more since as I build further to completion. So I will definitely keep it in mind.

  • Patrick
1 Like