Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Camera controller small problem

Discussion in 'Scripting' started by gk104, Dec 24, 2016.

  1. gk104

    gk104

    Joined:
    Apr 25, 2014
    Posts:
    57
    I'm working on a 2d game and having a problem scripting the camera controller.

    basically what i'm trying to do is to make an if statement to check that if the camera x position isn't as same as the main player x pos', move the camera on the X axis towards the player.

    problem is that the camera goes all blurry, because the camera move too much.

    Code (CSharp):
    1.     public void Camera_Controller()
    2.     {
    3.         float distance = Mathf.Abs(Vector2.Distance(player.position, transform.position));
    4.  
    5.         if (distance > 0)
    6.         {
    7.             if(player.position.x < transform.position.x)
    8.             {
    9.                 transform.position -= new Vector3(10*Time.deltaTime,0);
    10.             }
    11.             else
    12.             {
    13.                 transform.position += new Vector3(10*Time.deltaTime, 0);
    14.             }
    15.         }
    16.     }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    gk104 and APSchmidtOfOld like this.
  3. gk104

    gk104

    Joined:
    Apr 25, 2014
    Posts:
    57
    Thanks for your help.
    MoveTowards works like charm! so smooth and nice. what's the difference between MoveTowards and SmoothDamp?

    new code if it may be helpful for someone:

    Code (CSharp):
    1.     void Update()
    2.     {
    3.         Camera_Controller();
    4.     }
    5.  
    6.     public void Camera_Controller()
    7.     {
    8.         distance = Mathf.Abs(Vector2.Distance(player.position, transform.position));
    9.         Vector3 targetPos = new Vector3(player.position.x, transform.position.y, -10f);
    10.  
    11.         if(distance > 0)
    12.         {
    13.             transform.position = Vector3.MoveTowards(transform.position, targetPos , 2*Time.deltaTime);
    14.         }
    15.     }
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    SmoothDamp has "weight" to it, it's not a linear A to B movement.