Pausing a quaternion back and forth sin rotation based on time.time
Heya,
I'm a bit of a maths dunce trudging my way through a C# course and I'm trying to program a targeting cone which rotates on one axis (z) constantly, but pauses in place whenever the fire button (space) is held and charged up.
My current rotation code is as follows, 65f is the max rotation in either direction and 2f is the speed:
public void Metronome()
{
transform.rotation = Quaternion.Euler(0,0,65f * Mathf.Sin(Time.time * 2f))
}
And its called in my update function as follows:
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
//some irrelevant code here
}
else
{
Metronome();
}
It is rotating at a reasonable speed, and pausing in the update function when fire (space) is pressed but the thing is its position jumps forward to catch up with time.time whenever the fire button is released, the animation jump is pretty jarring and I'm trying to rectify it to make the rotating pick up from exactly the place it left off.
I'm sure it's an obvious fix, I mean It currently works well enough, I'm just terrified of quaternions (rotating there menacingly with their ominous 'w' values!). I've thought maybe using a coroutine to keep a separate sort of time value, or track the value as it changes with getKeyDown and getKeyUp but honestly I'm not sure and would appreciate any advice, or even alternate ways to do this!
Also, if anyone knows how to translate the amount of time to a function that proportionately shoots out projectiles/force in a cone I will give them exclusive rights to my soul in perpetuity - but of course this question is more pressing.
Many thanks!
Answer by Gallawagga · Nov 27, 2020 at 07:34 AM
I think I worked it out!
I just added a float variable that updates along with Time.deltaTime (which is only the time since the last frame, not the time since the game's beginning) while the function is running. It looks like this:
public void Metronome()
{
metroTime += Time.deltaTime;
transform.rotation = Quaternion.Euler(0,0,65f * Mathf.Sin(metroTime * 2f))
}
Probably not ideal, but I like how simple it is - though I am a complete beginner haha so it could be causing a memory leak for all I know. In any case would love feedback about it - and if anyone has an answer to that last projectile question the offer of my soul still stands.
Your answer
Follow this Question
Related Questions
Mobile Gyroscope, make Camera always rotating towards zero point using Quaternion 2 Answers
Using a directional vector to orient a sphere? 0 Answers
Quaternion AngleAxis on pitch give random small value on others axis 0 Answers
Help with suns rotation 0 Answers
Unity 2D rotation not smooth? 0 Answers