Untitled

 avatar
unknown
plain_text
2 years ago
1.9 kB
34
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class CameraScript : MonoBehaviour
{

    GameObject target;
    Camera cam;

    public float horizontalPadding = 3.0f;
    public float verticalPadding = 2.0f;

    float maxHorizontalDistance;
    float maxVerticalDistance;

    // Start is called before the first frame update
    void Start()
    {

        target = GameObject.FindGameObjectWithTag("Player");
        cam = GetComponent<Camera>();
        maxVerticalDistance = cam.orthographicSize - verticalPadding;
        maxHorizontalDistance = cam.orthographicSize * cam.aspect - horizontalPadding;

    }

    // Update is called once per frame
    void Update()
    {
        // Is player to far to the right?
        if (target.transform.position.x > transform.position.x + maxHorizontalDistance)
        {
            SetX(target.transform.position.x - maxHorizontalDistance);
        }
        // Too far to the left?
        else if (target.transform.position.x < transform.position.x - maxHorizontalDistance)
        {
            SetX(target.transform.position.x + maxHorizontalDistance);
        }

        // Too high up?
        if (target.transform.position.y > transform.position.y + maxVerticalDistance)
        {
            SetY(target.transform.position.y - maxVerticalDistance);
        }
        // Too low down?
        else if (target.transform.position.y < transform.position.y - maxVerticalDistance)
        {
            SetY(target.transform.position.y + maxVerticalDistance);
        }

    }

    void SetX(float newX)
    {
        transform.position = new Vector3(newX, transform.position.y, transform.position.z);
    }

    void SetY(float newY)
    {
        transform.position = new Vector3(transform.position.x, newY, transform.position.z);
    }
}
Editor is loading...