0
\$\begingroup\$

I am working on a small 2D platformer in Unity for my school project and I would like to lock my camera on Y axis (so it can move horizontally, but when the character jumps it doesn't follow the jump). I have found something on the internet, but I'm struggling with implementing it into my Smooth Camera Follow code that I currently have:

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 = GetComponent<Camera>().WorldToViewportPoint(target.position);
        Vector3 delta = target.position - GetComponent<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);
      
    }
}
New contributor
thrsarts is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
0
\$\begingroup\$

This is pretty trivial. Just save the locked y value you want into a variable, then override the y component of your destination point with that saved value.

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

private Camera _camera;
private float _fixedHeight;

void Start()
{
    // Do this once, so you're not searching for the component
    // multiple times every frame.
    _camera = GetComponent<Camera>();

    // Cache camera y position.
    _fixedHeight = transform.position.y;
}

void Update()
{
    if (target)
    {
        // Don't need the full viewport point if all you want is the z.
        float depth = Vector3.Dot(
                       target.position - transform.position, 
                       transform.forward
        );
        // I recommend caching depth too, and re-using the cached value,
        // to ensure rounding errors don't accumulate.
        
        Vector3 viewportFocus = new Vector3(0.5f, 0.5f, depth);
        Vector3 worldFocus = _camera.ViewportToWorldPoint(viewportFocus);

        Vector3 delta = target.position - worldFocus;
        Vector3 destination = transform.position + delta;

        // Override destination height.
        destination.y = _fixedHeight;

        transform.position = Vector3.SmoothDamp(
                                transform.position,
                                destination,
                                ref _velocity,
                                dampTime
        );          
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .