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

How Can Moon or Sun Follow Camera?

Discussion in 'Scripting' started by 1ht1baron, Jun 16, 2018.

  1. 1ht1baron

    1ht1baron

    Joined:
    Aug 15, 2017
    Posts:
    65
    I am making 2D enless runner. I have a moon. I want the moon follow camera. But it must slide to the left slowly. Also, it must follow on Y Axis without slide. My camera has a follow camera script.

    Code (CSharp):
    1.     private Vector2 velocity;
    2.  
    3.     public float smoothTimeY;
    4.     public float smoothTimeX;
    5.  
    6.     [SerializeField]
    7.     private float xMax;
    8.  
    9.     [SerializeField]
    10.     private float yMax;
    11.  
    12.     [SerializeField]
    13.     private float xMin;
    14.  
    15.     [SerializeField]
    16.     private float yMin;
    17.  
    18.     public GameObject player;
    19.  
    20.     void Start () {
    21.         player = GameObject.FindGameObjectWithTag ("Player");
    22.     }
    23.    
    24.  
    25.     void FixedUpdate () {
    26.         float posX = Mathf.SmoothDamp (transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX);
    27.         float posY = Mathf.SmoothDamp (transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeY);
    28.  
    29.         transform.position = new Vector3 (posX, posY, transform.position.z);
    30.         transform.position = new Vector3 (Mathf.Clamp (player.transform.position.x, xMin, xMax), Mathf.Clamp (player.transform.position.y+2.86f, yMin, yMax), transform.position.z);
    31.     }
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,514
    Well first and foremost, we don't know your entire setup, so we can't give an exact answer to this. I don't know if you reset your endless runner every so many units (basically moving your player back to origin), or any other scenario that may adjust how youd accomplish this.

    With that said...

    The general idea is this.

    You have a moving origin for the moon around which it animates. This can most easily accomplished by nesting the moon inside of a parent Transform/container.

    You move this origin/parent with your player/camera so that it is always near it (heck, in some situations you can use the camera as the parent... though this means you can't ease/damp the motion at all).

    Then the moving to left animation is just done locally within that parent.

    So as the camera moves right the moon is largely moving right with it, but slowly moving left as well relative to that overall rightward motion.
     
    Last edited: Jun 16, 2018
    1ht1baron, Doug_B and Joe-Censored like this.