Editing Unity2DCameraFollow to allow for camera offset
The Unity 2D packages comes with a script that you can plug in and it will follow your character. Awesome!
However, the camera follows the player and places them in the centre of the camera.
Would there be an easy way to edit this so that there is an offset, and the camera places the player in the bottom left instead of being in the dead centre?
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Camera2DFollow : MonoBehaviour
{
public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;
private float m_OffsetZ;
private Vector3 m_LastTargetPosition;
private Vector3 m_CurrentVelocity;
private Vector3 m_LookAheadPos;
// Use this for initialization
private void Start()
{
m_LastTargetPosition = target.position;
m_OffsetZ = (transform.position - target.position).z;
transform.parent = null;
}
// Update is called once per frame
private void Update()
{
// only update lookahead pos if accelerating or changed direction
float xMoveDelta = (target.position - m_LastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
if (updateLookAheadTarget)
{
m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
}
else
{
m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
}
Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
transform.position = newPos;
m_LastTargetPosition = target.position;
}
}
}
Answer by Kiou-23 · Dec 30, 2017 at 12:05 AM
Yeah, don't use the Unity assets, they're only bring more problems a 2d camera follow is fairly easy to code on your own make a CameraFollow script, and then add a reference to the transform of your player gameObject (drag and drop it in the inspector) Then you can update the camera position in the LateUpdate method (since lateUpdate gets called after Update, the camera will only move after the player has moved to prevent glicthces and jittering) in there you can simply set the camera position to be that of the player plus a certain offset if you need more helpI suggest you check a youtuber called Brackeys
Your answer
![](https://koobas.hobune.stream/wayback/20220612145224im_/https://answers.unity.com/themes/thub/images/avi.jpg)