Search code examples
c#animationunity-game-engineanimator

How to get back to the first position animatedly in unity?


I have a camera that I control it with the (W,A,S,D) keys...

What I want to do is that when press left mouse click ("Fire1") the camera turns back to the first position animatedly.

Is it possible to do it with Mecanim and create a dynamic animation file to do it?!

That's my code:

void Update () 
{
    if (Input.GetKey(KeyCode.W)) 
    {
        Cam.transform.Rotate (0, 0, 2);
    }

    if (Input.GetKey(KeyCode.S) )
    {
        Cam.transform.Rotate (0, 0, -2);
    }

    if (Input.GetKey(KeyCode.D)) 
    {
        Cam.transform.Rotate (0, 2, 0);
    }

    if (Input.GetKey(KeyCode.A)) 
    {
        Cam.transform.Rotate (0, -2, 0);
    }

My camera position and rotation at the start is (0,0,0) but when I control my camera these parameters change so I want my camera to turns back to the first position (0,0,0) animatedly when I press left mouse button...

Something like:

if (Input.GetButtonDown("Fire1")) 
{
    Cam.GetComponent<Animation> ().Play ();
}

Solution

  • Instead of the animation, you could smooth out the camera movement:

    Add the following variables to your script, the first one is used to control the amount of smoothness you want:

    public float smoothTime = 0.2f;
    private Vector3 velocity = Vector3.zero;
    

    And then:

    if (Input.GetButtonDown("Fire1")) {
        Vector3 targetPosition = new Vector3(0,0,0);
        Cam.transform.position = Vector3.SmoothDamp(Cam.transform.position, targetPosition, ref velocity, smoothTime);
    }