Big Ben GamerGuyKSPMC
Big Ben GamerGuyKSPMC

Reputation: 149

Move Camera in UnityScript 2d in C#

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;
    }
}

Upvotes: 0

Views: 5537

Answers (1)

chosendeath
chosendeath

Reputation: 106

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);
         }

     }
 }

Upvotes: 3

Related Questions