Search Unity

Follow Player in 2D Game

Discussion in '2D' started by siddharth3322, Mar 31, 2015.

  1. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    At present I am working on 2d side scrolling game. I want camera follow for player movement only in horizontal movement. Right now I have written this type of target following script

    Code (CSharp):
    1. public class SmoothFollow : MonoBehaviour
    2. {
    3.      public Transform target;
    4.      public float smoothness;
    5.      private Vector3 targetInitialPos;
    6.      void Awake ()
    7.      {
    8.          targetInitialPos = target.position;
    9.      }
    10.      void Update ()
    11.      {
    12.          Vector3 cameraPosition = target.position - targetInitialPos;
    13.          cameraPosition.y = 0f;
    14.          cameraPosition.z = -10f;
    15.          transform.position = cameraPosition;
    16. //        transform.position = Vector3.Lerp (transform.position , cameraPosition , Time.deltaTime * smoothness);
    17.      }
    18. }
    19.  
    Using above code it shows jerky movement of camera. Not smoother one that I want. Please give some suggestion in this.
     
    PlakiYT likes this.
  2. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    Here is the script I use on my camera to get smoother camera movement; http://pastebin.com/D6A0pQPn
    To disable Y position, just change the Vector3 to ingore the Y position of the player.
    Make sure to add the Player to the camera script as well.

    Hope it helps
     
  3. Jonathan-Watkins

    Jonathan-Watkins

    Joined:
    Mar 10, 2015
    Posts:
    125
  4. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    @Ivanskodje, Thanks for your help but I can't able to decide which value suited to my implementation.
    Using your script I am noticing totally wrong behaviour. I have also played with multiple values but didn't got succeed.
    Please help me to use your script.
     
    Ivanskodje likes this.
  5. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    Here you go; http://pastebin.com/rhyh2cJr
    This is a much simpler version of the first script I posted. This one will simply follow the player smoothly in the X direction.

    Just change the "constantYposition" to match your camera Y axis. This is the value that will not change, regardless of your character position. The camera will follow the target player (X axis), so make sure to use Unity to assign it a player transform (drag the player game object to the script so it looks something like this http://prntscr.com/6o3xug ).

    Hope it helps! :)
     
    theANMATOR2b likes this.
  6. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    After using you new code it does not behave correct at all.
    Following image illustrate where player is moving and continuous vibrate on screen.

    Screen Shot 2015-04-01 at 8.25.01 pm.png

    I want camera to be 0 in vertical movement and player need to be left hand side of screen.
    Please help me to use your script. I can't able to figure out where I am doing wrong.

    I played with every damping value but didn't got success.
     
  7. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    Are you programming in an 2D or 3D environment?
    Make sure X is left/right and Y is up/down in an 2D environment.

    I can't help any more unless you post your code / project here. :S

    If you don't know how to work with XY(Z) Vectors, I would highly recommend you play around with various tutorials on YouTube to learn the basics :)

    The game looks very nice though. Made from a tutorial or did you make everything yourself?
     
    theANMATOR2b likes this.
  8. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    I have used following screen for my player follow
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4.  
    5. // Add this script to the camera you want to follow the player
    6. public class CameraController : MonoBehaviour
    7. {
    8.     // Player (the Transform of whatever you want the camera to follow)
    9.     public Transform player;
    10.    
    11.     // Change this to match your game. This is the Y coordinate of where your camera will look.
    12.     // It will only follow the player left and right, so make sure you position this correctly! :)
    13.     public float constantYposition;
    14.    
    15.     // Increase to make the camera follow the player slower - or decrease for more instant gratification
    16.     public float damping = 0.5f;
    17.    
    18.     // Used to keep track of the players previous position
    19.     private Vector3 lastTargetPosition;
    20.    
    21.     // Sorry - I can't figure out what this is used for, as it apparently is never initialized.
    22.     // However, this needs to be here so we can ref it in the SmoothDamp thing. :S
    23.     private Vector3 currentVelocity;
    24.    
    25.    
    26.     // Use this for initialization
    27.     void Start ()
    28.     {
    29.         // Save player position as last player position
    30.         lastTargetPosition = player.position;
    31.        
    32.         // This will prevent the camera from following a parent - in case you added the camera as somethings child.
    33.         // (which makes the camera follow whatever parent)
    34.         transform.parent = null;
    35.     }
    36.    
    37.    
    38.     // Update is called once per frame
    39.     void Update ()
    40.     {
    41.  
    42.         if (!player) {
    43.             player = GameObject.FindGameObjectWithTag (GameConstants.TAG_MR_JUMP).transform;
    44.         } else {
    45.  
    46.  
    47.             // Camera follows the player smoothly with this
    48.             Vector3 newPos = Vector3.SmoothDamp (new Vector3 (transform.position.x, constantYposition, transform.position.z), player.position, ref currentVelocity, damping);
    49.        
    50.             newPos.z = -10f;
    51.             newPos.y = 0f;
    52.             // Change the position to the camera
    53.             transform.position = newPos;
    54.        
    55.             // Set player position as last camera position (helps us to give the effect of smoothly following the player)
    56.             lastTargetPosition = player.position;
    57.         }
    58.     }
    59. }
    Public variable value
    Constant YPosition = 0
    Damping = 0.5

    Link for game video :
    https://www.dropbox.com/s/j453wltivwogj17/MrJumpCameraController.mov?dl=0

    Now give me some suggestion. Where I am doing wrong?
    I really need your help.
     
  9. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    Ah, I believe I understand the problem. Your "player" is twitching a bit when it reaches the maximum damping distance towards the right from the camera, correct?

    I actually have a similar issue, but haven't prioritized fixing it as appearance and "visual looks" is the last parts of the puzzle when creating a game (at least for my project).

    If this was indeed the problem, I will look into it and post here when I figure it out! I am unfortunately on a tiny vacation (I prefer relax at home and do some programming! I know, I'm weird...) and should hopefully be back by Monday to check things out (unless someone have managed to find a fix for it!) :)

    Of course if I have time, I might be able to find a fix sooner, but no promises!
     
  10. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    @Ivanskodje , Thanks for your suggestions. I want camera follow smoothness.
    No problem if you reply me on monday. Enjoy your vacation :)
    But I am waiting for your reply. Please give me some suggestion in this.
     
    Ivanskodje likes this.
  11. RoyalCoder

    RoyalCoder

    Joined:
    Oct 4, 2013
    Posts:
    301
    Hi @siddharth3322 ,

    A easy way to achieve what you want:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class CameraJucator : MonoBehaviour {
    4.     public int yOffset = 5;
    5.     private Transform player;
    6.     void Awake()
    7.     {
    8.         player = GameObject.FindGameObjectWithTag("Player").transform;
    9.     }
    10.     void Update ()
    11.     {
    12.         transform.position = new Vector3(player.position.x + 7, player.position.y + yOffset, -30);
    13.     }
    14. }
    *And this is my personal script that I use, more advanced :
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.     /************************
    4.      *  CopyRight 2015
    5.      * Buraca Dorin
    6.      ***********************/
    7.     public class CameraJucator : MonoBehaviour
    8.     {
    9.         public Camera cameraP;     //MAIN CAMERA
    10.         public Transform jucator;    //PLAYER
    11.  
    12.         public float compesatieX = 7;  //OFFESET ON X
    13.         public float marimeCamera = 6f;  //CAMERA SIZE (ORTOGRAPHIC)
    14.         public float vitezaCam = 2f;     //CAMERA SPEED
    15.         public float marimeMaxima = 7.5f;  //MAX CAMERA SIZE
    16.         public float marimeMinima = 5.5f;  //MIN CAMERA SIZE
    17.  
    18.         void Update()
    19.         {          
    20.             marimeCamera = 2f + jucator.transform.position.y;
    21.             if (marimeCamera >= marimeMaxima)
    22.             {
    23.                 marimeCamera = marimeMaxima;
    24.             }
    25.  
    26.             if (marimeCamera <= marimeMinima)
    27.             {
    28.                 marimeCamera = marimeMinima;
    29.             }
    30.             transform.position = new Vector3(jucator.position.x + compesatieX, 4.5f, -50);
    31.             cameraP.orthographicSize = Mathf.Lerp(cameraP.orthographicSize, marimeCamera, Time.deltaTime / vitezaCam);
    32.         }
    33.     }
    34.  
    *I will repost the script in english to make'it more understandable ;) Hope this will help you ;)

    Cheers,
     
  12. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    @D0R1N , Thanks for your reply.
    But as per my consideration if I directly apply vector to camera tranform generated jerky behaviour.
    One more thing for my game I don't need orthographic size change during follow.
     
  13. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    I have found a fix that works for me;

    First go to Project Settings -> Time

    Then reduce the Fixed Timestep to 0.01 (previously 0.02).



    Its super smooth now!
     
    theANMATOR2b likes this.
  14. Stv3D

    Stv3D

    Joined:
    Dec 10, 2011
    Posts:
    34
    Hey siddharth3322,

    Make sure your Player is on the FixedUpdate() function if you are controlling it with physics.
    After that move the Camera Follow code to LateUpdate().

    Read here: http://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class CameraController : MonoBehaviour {
    5.  
    6.     public Transform target;
    7.  
    8.     Vector3 refVelocity = Vector3.zero;
    9.  
    10.     // Use this for initialization
    11.     void Start () {
    12.  
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void LateUpdate () {
    17.         transform.position = Vector3.SmoothDamp(transform.position, new Vector3(target.position.x, 0, -10f  ), ref refVelocity, 0.2f);
    18.     }
    19. }
     
    Ivanskodje likes this.
  15. Ivanskodje

    Ivanskodje

    Joined:
    Mar 29, 2015
    Posts:
    57
    Sweet! I knew there had to be something better than what I used. Learn something new every day :)
    Hope it works for siddharth too!
     
    theANMATOR2b likes this.
  16. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    Thanks friends, After reading all above details I am pretty sure I can able to solve this problem.
    I will reply you in short time because right now I am working on some other project.
     
  17. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    As per my experience for smooth movement following changes work from my side
    Fixed Time Step : 0.02
    Maximum Allowed Time : 0.02

    in Time Setting Inspector.

    Because there is glitch from rendering part not from physics part. So speed up value to this can change game behaviour.