We will keep going with the same game scene we left at the end of the previous recipe, so just stick with the instructions!
Back_Manager
.From a game logic perspective, the most important variable we are adding to the script is an Array[]
variable type that we use to manage the three panels that repeat endlessly in the background. To achieve that, add the following lines at the beginning of the script:
public Transform backBrick; private Transform[] backArray=new Transform[3]; private Transform thisChar; private float distance; private float farDistance; private Vector3 brickScale;
Start()
function we put the instructions to initialize the variables and create a service float
variable to help us make longer lines of code more readable. These instructions could be added to an Awake()
function instead of Start()
, but to keep things easy, we prefer to use the Start()
function.Start()
function of the script:thisChar = GameObject.Find ("Constructor").GetComponent<Transform>(); farDistance = 30.0f; brickScale=new Vector3(60,60,1); float xPosition;
for()
cycle to instantiate the panels in the scene; add them to the array and set their scale. The following code goes into the Start()
function too:for (int i=0; i<3; i++) { xPosition=(brickScale.x*i); backArray[i]=(Transform)Instantiate(backBrick,new Vector3(xPosition,0,farDistance),Quaternion.identity); backArray[i].localScale=brickScale; }
Update()
function we plan to run a routine that keeps repeating and checks the horizontal distance between the character and the background panels. For this reason, instead of coding the routine into the Update()
function itself, we make a custom function and then call that function in Update()
. The custom function name is CheckDistance()
and this is the code to be added to it:void CheckDistance(){ for (int i=0; i<3; i++) { distance=thisChar.transform.position.xbackArray[i].transform.position.x; if(Mathf.Abs (distance) > (brickScale.x * 1.5) &&distance > 0){ backArray[i].Translate( 3* brickScale.x,0,0); break; } if(Mathf.Abs (distance) > (brickScale.x * 1.5) &&distance < 0){ backArray[i].Translate(-3*brickScale.x,0,0); break; } } }
Update()
function and add a call to CheckDistance()
there using the following lines:void Update () { CheckDistance (); }
In case you are missing something, the following screenshot shows the complete BackgroundManager
script:
back_manager
. You can refer to the following screenshot:The scripts attached to back_manager
in the scene take care of instantiating the panels with the right position and scale. As the character moves left or right, the scripts check their position and decide how to translate the background panels so one is always behind the player. It just needs us to manually create a reference to the prefab to be used for the background panels, which is what we did with the last step of the recipe.
3.147.80.100