- Home /
2D Style Camera, Shifting at Screen Edge
Hey, I'm pretty new to scripting and Unity but I'll try my best to convey my issue.
My question, if you wish to help:
In a 2D-style platformer, how can the camera stay fixed on a "room" until the character reaches a side of the screen and walks off, prompting the camera to shift to the section he's entering?
I think I could start off with either:
Triggerwalls in each room that shift camera over
Calculate screen edges in real world space, if player exits shift that way
Set empty object in center of room, raycast to player
Any thoughts?
Answer by Mortoc · Jun 11, 2012 at 02:53 AM
I think the easiest way would be to have a script keep track of the player's position in view space since it sounds like you'll wanna tweak this behavior.
void Update() {
Vector3 viewPosition = camera. WorldToViewportPoint(player.transform.position);
if( viewPosition.x > 0.9f ) // move right
else if( viewPosition.x < 0.1f ) // move left
// etc
}
That sounds great! I'll have to try it when I get home from class. I'm guessing vertical would be similar but with viewPosition.y, but I'm wondering how to set up camera movement after that. Would I have a smooth movement of the camera in the world equal to or at least related to view width or height?
I got the detection on the sides working, but I'm trying to set up a translate of the camera in the direction. I figured that something like Camera.ViewportToWorldPoint could be used to calculate the screen width and height in world units and set the result as the distance in my transform.Translate, but it's not moving that distance. Any other suggestions on a reliable tracking of viewport width for the translation?
EDIT: Actually, I got it working, generally. Just had to fix the z in ViewportToWorldPoint