- Home /
How do I rotate an object over time outside the Update method?
I have an object that detects if the player hits it (a trigger zone), and if the player does hit it, the player should rotate. My trigger zone has the following code:
void OnTriggerEnter(Collider other)
{
if(isRotatorTrigger)
{
other.transform.Rotate(Vector3.forward, -90.0f * Time.deltaTime);
}
}
This doesn't work, and I'm fairly certain it's because OnTriggerEnter() is called once, instead of every frame like Update(). That makes Time.deltaTime not work. Since I'm in a method that is called only once, how do I make the player rotate smoothly over time? I tried to make a coroutine, but that didn't work. (That could be because I'm not too savvy with coroutines.) All my searching leads me to answers that use Time.deltaTime and are locating in the Update() method. Do I need to restructure my program and put the rotation in the Update() method?
Answer by mattyman174 · Feb 20, 2014 at 01:55 AM
You need to create a Method that is called in Update() so that it recieves the same amount of calls as Update() does. Then just use a simple boolean Variable to detect if we want to Rotate the Player and do the Rotation within that new Method. Like so.
using UnityEngine;
using System.Collections;
public class testScript : MonoBehaviour {
private bool isRotatorTrigger = true;
private bool canRotatePlayer = false;
private Collider triggeringCollider;
void Update()
{
RotatePlayer();
}
void OnTriggerEnter(Collider other)
{
triggeringCollider = other;
if (isRotatorTrigger)
canRotatePlayer = true;
}
protected void RotatePlayer()
{
if(canRotatePlayer)
triggeringCollider.transform.Rotate(Vector3.forward, -90.0f * Time.deltaTime);
}
}
Excellent! That worked. However, the player now rotates infinitely. Now I need to find a way to detect when it has reached -90 degrees (or whatever angle), then set canRotatePlayer to false. I'll do some research on that. Thanks!
Yeh obviously i left out alot of detail in that example, but you might also want to think about checking if the Collider that the RotatePlayer() method is trying to Rotate is the exact collider you want, unless of course its just a generic function that rotates anything that hits the Trigger of course.
Good luck.
Answer by xt-xylophone · Feb 20, 2014 at 01:49 AM
You could try OnTriggerStay? It gets called WHILE theres something touching it. Or set a bool to true onEnter and false onExit and then in Update rotate if that bool is true.