I’m trying to rotate a door with the following code, it works when the methods are called in Update but not in Interact, when done in Interact the door only rotates one way.
Also for some reason bool isOpen will get changed twice
//From answers.unity.com
IEnumerator RotateMe(Vector3 byAngles, float inTime)
{
var fromAngle = transform.rotation;
var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
for (var t = 0f; t <= 1; t += Time.deltaTime / inTime)
{
transform.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
yield return null;
}
}
//Rotates an object correctly when called in Update
void Update () {
if(Input.GetKeyDown("e")){
StartCoroutine(RotateMe(Vector3.up * 90, 0.8f));
}
if(Input.GetKeyDown("q")){
StartCoroutine(RotateMe(Vector3.up * -90, 0.8f));
}
}
//Does not work when called in a method like so
void Interact()
{
Debug.Log(tf.rotation.y);
if (!isOpen)
OpenDoor();
if (isOpen)
CloseDoor();
}
void CloseDoor()
{
StartCoroutine(RotateMe(Vector3.up * -90, 0.8f));
isOpen = false;
Debug.LogError(isOpen.ToString());
}
void OpenDoor()
{
StartCoroutine(RotateMe(Vector3.up * 90, 0.8f));
isOpen = true;
Debug.LogError(isOpen.ToString());
}
//Interact method gets called like this
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
RaycastHit hit;
if (Physics.Raycast(transform.position, cam.transform.forward, out hit, 10))
{
if (hit.collider.gameObject.tag == "Interactable")
{
Debug.Log("Looking at interactable object" + hit.collider.gameObject.tag);
hit.collider.gameObject.SendMessageUpwards("Interact");
Debug.Log("Used interactable object");
}
}
}
}
}