- Home /
Keeping a Camera focused on the GameObject in a 2D Game
HI everybody,
I am revisiting a game I created a while ago. My question is this: How do I make the camera stay focused on the central perspective as the action moves to the right? right now, I have a scenario where the left edge of the screen will kill the player if it touches him. It isn't focused on him because if it was, it would move when he jumped, which would expose parts of the scene I don't want the user to see. The problem is that if he moves to far to the right, he can go past the visible threshold...
It seems like a simple enough solution, and here is what I am thinking. You calculate the distance between the player and the gamObject, in this case, the Camera. When the distance exceeds whatever appropriate distance, then the gamObject increases its distance back to a specified distance "Home" distance.
it would look a little bit like this:
var distance;
var target : Transform;
var cameraTransform : Transform;
var initialDistance = 3.0;
function Awake()
{
cameraTransform = transform;
}
function Start()
{
target = GameObject.FindWithTag("NAME").transform;
}
function Update()
{
var distance = (target.position - cameraTransform.position).magnitude;
}
then a bunch of if statements etc. describing the when to add the distance from current distance.
Does that make sense? Am I setting that up correctly in your eyes??
Thanks for your help everybody.
As the player, I'd probably find it annoying if the camera lagged behind me then zoomed back in with me as the focus only to lag behind me again as I moved to the right. Would it work well in your game if you used the player as your focus but ignored up/down movements on the camera?
@getyour411 it is essentially a simple side scrolling game I worked on a long time ago. It doesn't zoom. It should just push the right edge further in front of the player. my goal is to have the player not go past the right edge of the screen. Currently, the player just goes beyond the right edge and is not seen.
What you describe does not make much sense to me. Not sure of your game mechanic, but I one idea is to convert the player's position into a viewport coordinate (Camera.WorldToViewportPoint()). Viewport coordinates go from (0,0) in the lower left to (1,1) in the upper right. So as the player passes beyond the middle of the screen (Viewport x coordinate of 0.5), you would increase the scroll speed of the camera. I'd likely scale it higher depending on how close to the edge (x coordinate of 1.0), and perhaps smooth the increase.
thanks, @robertbu. I am not extremely knowledgable of all aspects of code. This sounds like a great solution to me. Thanks for pointing me in a new direction.