Home > front end >  I want to finish the level with 2 players at the door. How do I do it?
I want to finish the level with 2 players at the door. How do I do it?

Time:08-26

Here is my game I have 2 players and I want them both to go to the door to finish the level

here is my code for the trigger

`

private AudioSource finishSound;

private bool levelCompleted = false; //play the audio once
void Start()
{
    finishSound = GetComponent<AudioSource>();
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.name == "Player1" && !levelCompleted)
    {
        CompleteLevel();
        levelCompleted = true;
        Invoke("CompleteLevel", 1.5f); //delay finish
    }
}

private void CompleteLevel()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex   1);

}

}`

I know this code is only for one Player. How do I do it requiring 2 players at the door to finish the level?

CodePudding user response:

An approach for this would be to cache the players and check against the total count. To see if it's a player, I'd advice to use tags instead of using the name of the object for a lot of reasons. I assume, the tag "Player" is used to identify the player.

List<GameObject> players = new List<GameObject>();

private void OnTriggerEnter2D(Collider2D collision)
{
    // Add a new player if they enter the trigger
    if (collision.gameObject.CompareTag("Player") && !players.Contains(collision.gameObject))
    {
        players.Add(collision.gameObject);
    }

    // Both players are in the trigger
    if (players.Count == 2 && !levelCompleted)
    {
        CompleteLevel();
        levelCompleted = true;
        Invoke("CompleteLevel", 1.5f); //delay finish
    }
}

private void OnTriggerExit2D(Collider2D collision)
{
    // Remove a player if they leave the trigger again
    if (collision.gameObject.CompareTag("Player") && players.Contains(collision.gameObject))
    {
        players.Remove(collision.gameObject);
    }
}

If you have a varying count of players, you probably don't want to hard code the amount of players in a trigger. You should have a total count somewhere to check against. A game manager of sorts, that tracks the expected amount of players.

CodePudding user response:

One way would be to create flags for each player, not one. When player one enters the trigger, you set playerOneCompleted = true. Then, you check if second player also completed. If that's the case finish the game if not, do nothing.

What you would need to add is the method OnTriggerExit2D to set flags of respective players to false when they exit the area.

Since the code you presented is inside the player, I would advise moving it to the door's trigger, so you can reference both players more easily.

  • Related