- Home /
2D Camera Follow boundaries
alright so I'm trying to create a Camera that follows the player until it hits the edge of the map in which case it will stay inside the scene, I watched a video on it and the yAxis boundaries are good, but the xAxis boundaries are stopping too soon from the actual xAxis border.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraFollow : MonoBehaviour {
public Transform followTransform;
public BoxCollider2D MapBounds;
private float xMin, xMax, yMin, yMax;
private float camX, camY;
private float camOrthsize;
private float cameraRatio;
private Camera MainCam;
private void Start()
{
xMin = MapBounds.bounds.min.x;
xMax = MapBounds.bounds.max.x;
yMin = MapBounds.bounds.min.y;
yMax = MapBounds.bounds.max.y;
MainCam = GetComponent<Camera>();
camOrthsize = MainCam.orthographicSize;
cameraRatio = (xMax + camOrthsize) / 2.0f;
}
void FixedUpdate()
{
camY = Mathf.Clamp(followTransform.position.y, yMin + camOrthsize, yMax - camOrthsize);
camX = Mathf.Clamp(followTransform.position.x, xMin + cameraRatio, xMax - cameraRatio);
this.transform.position = new Vector3(camX, camY, this.transform.position.z);
}
}
Answer by RyanKelly23 · May 19 at 09:19 AM
As far as I know, you can do this with cinemachine and virtuel cameras. There's a guy on YouTube who's made a series about recreating Zelda in unity, in which he, among other things, covers this! FMC4ME Login Page
Your answer
![](https://koobas.hobune.stream/wayback/20220613060729im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Camera Border Follow 1 Answer
Move camera on Z axis instead of Y? 0 Answers
Sprinting camera movement? (C#) 1 Answer