Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- // Add this script to the camera you want to follow the player
- public class CameraController : MonoBehaviour
- {
- // Player (the Transform of whatever you want the camera to follow)
- public Transform player;
- // Change this to match your game. This is the Y coordinate of where your camera will look.
- // It will only follow the player left and right, so make sure you position this correctly! :)
- public float constantYposition;
- // Increase to make the camera follow the player slower - or decrease for more instant gratification
- public float damping = 0.5f;
- // Used to keep track of the players previous position
- private Vector3 lastTargetPosition;
- // Sorry - I can't figure out what this is used for, as it apparently is never initialized.
- // However, this needs to be here so we can ref it in the SmoothDamp thing. :S
- private Vector3 currentVelocity;
- // Use this for initialization
- void Start()
- {
- // Save player position as last player position
- lastTargetPosition = player.position;
- // This will prevent the camera from following a parent - in case you added the camera as somethings child.
- // (which makes the camera follow whatever parent)
- transform.parent = null;
- }
- // Update is called once per frame
- void Update()
- {
- // Camera follows the player smoothly with this
- Vector3 newPos = Vector3.SmoothDamp(new Vector3(transform.position.x, constantYposition, transform.position.z), player.position, ref currentVelocity, damping);
- // Change the position to the camera
- transform.position = newPos;
- // Set player position as last camera position (helps us to give the effect of smoothly following the player)
- lastTargetPosition = player.position;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement