Reputation: 11327
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationPlay : MonoBehaviour
{
public GameObject head;
public GameObject[] cameras;
private Animator anim;
private bool started = true;
private float animationLenth;
private bool rotateHead = false;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
private void Update()
{
if(started == true)
{
anim.enabled = true;
anim.Play("New State", 0, 0);
animationLenth = anim.GetCurrentAnimatorStateInfo(0).length;
StartCoroutine(AnimationEnded());
started = false;
}
if (rotateHead == true)
{
cameras[0].SetActive(false);
cameras[1].SetActive(true);
anim.enabled = false;
head.transform.localRotation = Quaternion.Lerp(head.transform.localRotation, Quaternion.Euler(head.transform.localRotation.x, head.transform.localRotation.y, 0f), 1.0f * Time.deltaTime);
}
}
IEnumerator AnimationEnded()
{
yield return new WaitForSeconds(animationLenth);
anim.enabled = false;
rotateHead = true;
}
}
The problem is in this part :
if (rotateHead == true)
{
cameras[0].SetActive(false);
cameras[1].SetActive(true);
anim.enabled = false;
head.transform.localRotation = Quaternion.Lerp(head.transform.localRotation, Quaternion.Euler(head.transform.localRotation.x, head.transform.localRotation.y, 0f), 1.0f * Time.deltaTime);
}
I'm making the cameras switching before the rotation even start, what I need is somehow to make the camera switching when the rotation is end. Not after the rotation start but when the rotation is end.
Upvotes: 1
Views: 32
Reputation: 945
Since you know what rotation you want to finish at, you can change cameras once you have reached that rotation.
Create and initialize a variable outside of the Update method:
private bool isFinishedTurning = false;
Then check whether the turn is completed in your update method and change cameras if it is complete:
if (rotateHead == true) {
Quaternion targetRotation = Quaternion.Euler(head.transform.localRotation.x, head.transform.localRotation.y, 0f);
head.transform.localRotation = Quaternion.Lerp(head.transform.localRotation, targetRotation, 1.0f * Time.deltaTime);
// Check whether the current localRotation is the same as the target rotation
if (head.transform.localRotation == targetRotation) {
isFinishedTurning = true;
}
}
// If the rotation is complete, swap cameras and disable animation
if (isFinishedTurning == true) {
cameras[0].SetActive(false);
cameras[1].SetActive(true);
anim.enabled = false;
isFinishedTurning = false;
}
Upvotes: 1