want to know that how mathf.movetowards works, i tried to play around it and have some issues. i want to make the camera moves from player to target places along with zooming upon triggered and vise versa, while smooth follow(camera changes target) works, smooth zooming doesn't work. i place the movetowards code to ontriggerenter/exit, but it doesn't work as intended as it only zoom for frames. However, if i place it at update side, the zooming doesn't work at al.
code provided for more infomation.
public class Disable : MonoBehaviour {
GameObject player;
GameObject Camera;
public Transform placeHolder;
public float smoothTime = 2f;
public float adjustSize;
public float originalSize = 6.5f;
public float targetOrtho;
public Vector3 velocity;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
Camera = GameObject.FindGameObjectWithTag("MainCamera");
}
private void Start()
{
targetOrtho = originalSize;
}
void Update()
{
Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, targetOrtho, smoothTime * Time.deltaTime); //doesn't work
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject == player)
{
Camera.GetComponent<Camera2DFollow>().target = placeHolder;
targetOrtho = adjustSize;
//Camera.GetComponent<Camera>().orthographicSize = adjustSize; //works but only changes the size without smooth
//Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, adjustSize, smoothTime * Time.deltaTime); //works but only did for a few frames( not completely)
}
}
void OnTriggerExit2D(Collider2D other)
{
Camera.GetComponent<Camera2DFollow>().target = null;
targetOrtho = originalSize;
//Camera.GetComponent<Camera>().orthographicSize = originalSize; //works but only changes the size without smooth
//Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, originalSize, smoothTime * Time.deltaTime); //works but only did for a few frames (not completely)
}
Mathf.MoveTowards
like a fire-and-forget tweening method: "I want you to start moving this object and continue moving this object over many frames until it reaches this target" - but it can't do that. It's just a math function to compute one new number from the numbers you give it. It has no concept of what object to apply that number to. This is the same misunderstanding described in this earlier Q&A about the vector version ofMoveTowards
- you can use a similar coroutine strategy to solve it. – DMGregory Mar 28 '19 at 14:22