- Home /
How to have camera follow player unless it hits a boundary
I'm currently making a top-down 2D game. The way I want the player and camera movement is much like the game undertale. My player can move freely within a set of boundaries. I want my camera to follow the player and keep the player centered to it. But if the camera hits the boundaries and stops moving, I want the player to be able to keep moving up until the boundaries as well even if it means leaving the middle of the camera. I then want the camera to go back to following the player in the center if it's not hitting any boundaries anymore.
the code I used to follow the player and stay centered was this -
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraControls : MonoBehaviour { public GameObject player; private Vector3 offset = new Vector3(0, 0, -10);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}
this did a pretty good job, but unfortunately, it neglects the boundaries I have set for the camera in another script in favor of following the player and keeping the player centered in the camera view.
Answer by KloverGames · Nov 18, 2021 at 01:28 PM
You can detect collisions by using OnCollisionEnter2D(Collision col).
Make sure you have a boolean to tell when you crossed the boundary
When you cross the boundary, set the cameraFollow variable to false.
As you can see, I've added an if statement in the LateUpdate() function for you that says whenever cameraFollow is true, the camera will follow the player's position.
So in OnCollisionEnter2D(), we set it to false because the player passed a boundary.
bool cameraFollow;
void OnCollisionEnter2D(Collision col)
{
if(col.gameObject.tag == "Boundary")
{
cameraFollow = false;
}
}
void LateUpdate()
{
if (cameraFollow)
{
transform.position = player.transform.position + offset;
}
}
Thank you so much! with a little tweaking this seems to work very well.
I have 2 follow-up questions. You have the boundary as an object with a tag, my boundaries were made with coding and the axes. What object do you suggest I make the boundaries with?
My second question, Unity is giving me an error on the OnCollisionEnter2D. Script error: OnCollisionEnter2D This message parameter has to be of type: Collision2D
You can make the boundary a cube and scale it bigger or smaller. Just disable the MeshRenderer component in the hierarchy afterwards.
For the second question, I’m not sure if you are familiar with parameters but a parameter is what’s inside of the parenthesis
void OnCollisionEnter2D(parameter variableName)
So change the parameter like this
void OnCollisionEnter2D(Collision2D col)
Let me know if what I said was confusing, I will explain it easier.