简体   繁体   中英

Unity2D camera zoom out by the distance of player to an object, Zoom in when it gets further away

I'm working on a side-scroller 2D plataform game, and I have a moment where there's a focus in the background in which i want to show to the player for an "aw" moment, and i want to zoom out the camera to show that moment and then zoom back in again. I guess you could say to do the same like Death's Gambit or hollow Knight when the object they want to show is too big for the size of the camera.

Tried to get the transform from the player in a certain area and calculate the distance to the point where i want the camera size to go to the max, and then calculate a percentage out of it to add multiplied by size difference but it would break the view port making it spazz out or zooming out to the max unity allowed.

The expected result is to make the camera zoom out with the distance to a certain point in the world, passing that point it stops zooming out, going backwards should zoom back in to the player with the initial OrtographicSize.

Thank you for the Help!

You can do:

public Transform Target1;
public Transform Target2;

public float sensetivity = 1f;
public float maxOrthographicSize = 10f;

Camera thisCam;
float minOrthographicSize = 5f;

private void Start() {
    thisCam = GetComponent<Camera>();
    minOrthographicSize = thisCam.orthographicSize;
}
void Update()
{
    thisCam.orthographicSize = minOrthographicSize + Mathf.Clamp(Vector2.Distance(Target1.position, Target2.position) * sensetivity, 0f, maxOrthographicSize);
}

In this solution minOrthographicSize can only happen if Target1 and Target2 are in the same position, to change that you can do:

public Transform Target1;
public Transform Target2;

public float minOrhtographicDistance = 5f;
public float sensetivity = 1f;
public float maxOrthographicSize = 10f;

Camera thisCam;
float min = 5f;

private void Start() {
    thisCam = GetComponent<Camera>();
    min = thisCam.orthographicSize;
}
void Update()
{
    thisCam.orthographicSize = min + Mathf.Clamp((Vector2.Distance(Target1.position, Target2.position) - minOrhtographicDistance) * sensetivity, 0f, maxOrthographicSize);
}

In this solution, the orthographic size will be minOrthographicSize for minOrhtographicDistance distance and then would change depending on the distance between targets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM