Time for actioning – attach the LookAtPlayer camera script

This simple script makes the camera look at Player. The camera does not move. It simply rotates so it's always looking at Player no matter how close or far away it is.

Attach this script to LookAt Camera in the Hierarchy panel:

Time for actioning – attach the LookAtPlayer camera script

What just happened?

Let us analyze the code that we just saw:

Line 6: private Transform playerPosition;

  • The variable playerPosition will store the Transform information of Player
  • This means that every frame, the Transform x, y, z position of Player is updated and stored in the variable playerPosition

Line 10: playerPosition = GameObject.Find("Player").transform;

  • In order to store the transform position of Player, the script first needs a reference of the Player GameObject by using GameObject.Find("Player")
  • Then the transform position of Player is retrieved and stored in the variable playerPosition

Line 13: void LateUpdate( )

Lookup LateUpdate in Scripting Reference, here's a quote:

...a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.

Line 15: transform.LookAt(playerPosition);

  • The LookAT() method is available in the Transform class
  • This is the method that makes the camera's transform rotation change so it's always looking at the target, which is the transform position of Player
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.99