- Home /
Run a script in 3 seconds on mouse click
I WANT TO DO IT : The object swings from side to side in 3 seconds when click the left mouse button, then stop swinging.
Here is my swinging script. Could you tell me what to put here?
using UnityEngine;
using System.Collections;
public class Swinging : MonoBehaviour {
public float speed = 1.0f;
public float maxRotation = 10.0f;
void Update() {
transform.rotation = Quaternion.Euler(0.0f, 0.0f, maxRotation * Mathf.Sin(Time.time * speed));
//transform.rotation = Quaternion.Euler(0.0f, 0.0f, maxRotation * (Mathf.PingPong(Time.time * speed, 2.0f)-1.0f));
}
}
Answer by michi_b · Nov 06, 2018 at 01:46 PM
Just save the time you last clicked and check each frame whether you are still in the duration of the swing. Here's that solution implemented as a Coroutine. You could also do all that in Update(), but then you would have to unnecessarily add state variables in class scope.
using UnityEngine;
using System.Collections;
public class Swinging : MonoBehaviour
{
public float speed = 1.0f;
public float maxRotation = 10.0f;
public float swingDuration = 3f;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(Swing(swingDuration));
}
}
private IEnumerator Swing(float duration)
{
float startTime = Time.time;
float endTime = startTime + duration;
while (Time.time < endTime)
{
float timeSinceStart = Time.time - startTime;
transform.rotation = Quaternion.Euler(0.0f, 0.0f, maxRotation * Mathf.Sin(timeSinceStart * speed));
yield return null;
}
}
}
Answer by UnityCoach · Nov 06, 2018 at 01:56 PM
First, here are some clues:
Sine goes from -1 to 1.
Sin (0) = 0
Sin (0.5f * PI) = 1
Sin (PI) = 0
Sin (1.5f * PI) = -1
Sin (2 * PI) = 0
When Time.time = ~3.14116, you have made one swing (left or right) and come back to neutral. Then when Time.time = ~3.14116 * 2, you'll have made one swing in the other direction and come back to neutral.
You want the animation to go forth and come back within 3 seconds.
So using Mathf.Sin(Time.time / PI * N), you get a value going from 0 to +1 to 0 to -1 to 0 again, in twice N seconds.
For instance, if you want a full cycle to last 3 seconds :
Mathf.Sin(Time.time / Mathf.PI * 1.5f)
Your answer
