Advertisement
Guest User

CameraController (Smooth, X direction)

a guest
Apr 1st, 2015
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  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.         // Camera follows the player smoothly with this
  42.         Vector3 newPos = Vector3.SmoothDamp(new Vector3(transform.position.x, constantYposition, transform.position.z), player.position, ref currentVelocity, damping);
  43.  
  44.         // Change the position to the camera
  45.         transform.position = newPos;
  46.  
  47.         // Set player position as last camera position (helps us to give the effect of smoothly following the player)
  48.         lastTargetPosition = player.position;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement