0

I have just started programming Unity 2d, and I have faced one large problem: How do I move the camera? The script is attached to the object "player". I want it to move with the player. Thanks!

using UnityEngine;
using System.Collections;
 
public class PlayerController : MonoBehaviour
{
    public float speed = 10; //Float for speed
    public string hAxis = "Horizontal";
 
    void FixedUpdate ()
    {
        if (Input.GetAxis (hAxis) < 0) //Left
        {
            Vector3 newScale = transform.localScale;
            newScale.y = 1.0f;
            newScale.x = 1.0f;
            transform.localScale = newScale;
        } 
        else if (Input.GetAxis (hAxis) > 0) //Right
        {
            Vector3 newScale =transform.localScale;
            newScale.x = 1.0f;
            transform.localScale = newScale;       
        }
        //Position transformation
        transform.position = transform.position + transform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
    }
}

1 Answer 1

3

Without any scripts, you could just drag the Camera GameObject to be a child of the player and the camera would start following the player position.

For a script, try this, set player as the target.

using UnityEngine;
 using System.Collections;

 public class SmoothCamera2D : MonoBehaviour {

     public float dampTime = 0.15f;
     private Vector3 velocity = Vector3.zero;
     public Transform target;

     // Update is called once per frame
     void Update () 
     {
         if (target)
         {
             Vector3 point = camera.WorldToViewportPoint(target.position);
             Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
             Vector3 destination = transform.position + delta;
             transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
         }

     }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

But is I attach main camera to object, screen is blue!
Check transform of the camera as a child of the player, make sure values for x and y are 0 (same position as player) and z is negative (behind player).
Look in Camera component, check for Size property, change that value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.