- Home /
Question by
Jacho_Mendt · Dec 06, 2017 at 09:18 AM ·
cameraunity 2dcamera movementviewport
Move the camera in 2D when target reaches bounds. Is there a better way?
Hello,
I've created a code snippet that allows the camera to move when the player reaches defined bounds inside the viewport (sort of what happens in old school rpg games like Final fantasy 6).
This code works perfectly, but I feel it could be further optimized. Does anyone have a suggestion?
Code:
void Update () {
//resize the field of view instead of the dimensions of the screen
cam.orthographicSize = (Screen.height / 100f)/scale;
//target is the transform of the gameObject that is focused by the camera
if (target)
{
//converts the coordinates of the target from world to viewport
//(range: 0-1, the center where the camera is positioned is always 0.5,0.5,z)
Vector3 targetVPPos = cam.WorldToViewportPoint(target.position);
/*if the target is outside the bounds defined by [range,1-range]
in viewport coordinates, returns by how much.
returns a negative float if targetVPPos.x (or .y)
is smaller than the lower bound, positive if it's bigger
than the higher bound, or 0*/
float deviationX = (Mathf.Clamp01((targetVPPos.x - range) * -1)* -1) + (Mathf.Clamp01(((1 - range) - targetVPPos.x) * -1));
float deviationY = (Mathf.Clamp01((targetVPPos.y - range) * -1)* -1) + (Mathf.Clamp01(((1 - range) - targetVPPos.y) * -1));
Vector3 deviationV3 = new Vector3(deviationX, deviationY, 0f);
if(deviationV3 != Vector3.zero)
{
/*add deviationV3 to a vector defining the camera position in the viewport
(constant, the camera is ALWAYS in the middle of it
then convert it in game coordinates*/
deviationV3 = cam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, -10f) + deviationV3);
/*Lerp from current camera position to the new position
to achieve a smooth transition.
if that is not required, changing the position
of the camera transform is sufficient*/
transform.position = Vector3.Lerp(transform.position, deviationV3, speed);
}
}
}
Comment