Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Camera follow the player.. HELP

Discussion in 'Scripting' started by engelcj, Aug 2, 2015.

  1. engelcj

    engelcj

    Joined:
    May 20, 2014
    Posts:
    122
    Hello everyone.

    I need get that my camera follow my character always leaving a margin of height above the character. I want this event is active after to give a click.

    An example to follow is the game of "Into the Circle", when the player it's launched, the camera follows the character always leaving a margin of height between the character and the camera.

    See the video:


    This is my code:

    Code (CSharp):
    1. if (Input.GetMouseButtonDown (0)) {
    2.  
    3. // This does not give me the result I want
    4. camera.transform.position = new Vector3 (0, player.transform.position.y / 2, -10);
    5. }
    6.  
    7. }
     
  2. HiddenMonk

    HiddenMonk

    Joined:
    Dec 19, 2014
    Posts:
    987
    Maybe something like (not tested)
    Code (CSharp):
    1. float height = 5f;
    2. float speed = .2f;
    3. Vector3 targetCamPosition;
    4.  
    5. Void Start()
    6. {
    7.     targetCamPosition = camera.transform.position;
    8. }
    9.  
    10. void Update()
    11. {
    12.     if (Input.GetMouseButtonDown (0))
    13.     {
    14.         targetCamPosition = camera.transform.position + (Vector3.up * height);
    15.     }
    16.  
    17.     camera.transform.position = Vector3.Lerp(camera.transform.position, targetCamPosition, speed * Time.deltaTime);
    18. }
    People might comment on how the lerp I am doing is wrong, but it isnt, it just might not give the result you are expecting. You can look online for different ways to use lerp, such as here http://www.blueraja.com/blog/404/how-to-use-unity-3ds-linear-interpolation-vector3-lerp-correctly
    Sorry if I misstyped something or the logic is wrong. Writing code on a tablet is painful.
     
    Last edited: Aug 2, 2015
  3. engelcj

    engelcj

    Joined:
    May 20, 2014
    Posts:
    122
    @HiddenMonk Thank you very much for the reply. The code did not work as I want, but I managed to give me an idea and now works :)