We need to put in walls for our game, so I will use the ones from the Pong game.
They will have similar import settings to the other Lightcycle sprites.
Import Settings for WallHorizontal:
We need to place four walls around our grid, which will involve positioning and scaling each of them. I named mine WallTop, WallBottom, WallLeft, and WallRight. Once you have them all, select the four walls, and add a Box Collider 2D. It will need the “Is Trigger” box checked. Your size settings might be different, depending on how you scale your walls, by the way!
Box Collider 2D for walls:
We would like to have the game ask if you want to play again after someone hits a wall. My favorite way to do this is based on code from this site:
https://answers.unity.com/questions/517275/how-to-add-play-again-or-quit-after-you-win.html
We will create an OnGUI function, which will fire every time the interface is redrawn. We only want it to happen when the game ends, though, so we’ll use a variable to keep track of that. Add the variable atEnd to the top of our Move script, and we will use that to track when the game ends. This will be a boolean variable, which can only be set to true and false.
atEnd variable added to Move script:
After we collide with a wall, we need to stop both players moving, and set the atEnd variable to true. We stop the players by setting the velocity vectors of their Rigidbody2D to a new vector. This is all still in the Move script. You'll have to replace your current OnTriggerEnter2D, because we cannot destroy the player anymore. (It would destroy the player, which would never fire the OnGUI event since it doesn't exist!)
OnTriggerEnter2D in Move script:
Finally, we can get to the part where we actually create the buttons. This is in an OnGUI function, which fires on each redraw. If we have actually ended the game, we need to create the text that the game is over and the two buttons for playing again or quitting. We organize this in a “Group”, which puts all the elements together.
We need to include SceneManagement at the top first.
Using commands for Move script:
In all of these GUI functions, the first argument is the x position, the second is the y position, the third is the width, and the fourth is the height.
OnGUI function in Move script:
And I think we have it!
Text and buttons when players collide with walls or edges: