How Do I Adjust Values Over A Gradual Amount of Time ?
Hi
I'm currently working on a Player Controller Script, that allows the Player to orbit there camera around the player in the horizontal and vertical axis's.
But I am having a small issue when it comes to resetting the camera after the player is finished orbiting. It resets, but it is an instant reset. Which from Player feedback is quiet jarring.
I was looking to add a small delay over time say 2 seconds, in which the camera resets to the desired position
Here is the current code
void OrbitTarget(){
if(Input.GetKeyUp(KeyCode.Mouse2)){
Debug.Log("Reset Orbit On Middle Mouse Wheel Realease");
orbit.yRotation = -180;
orbit.xRotation = -15;
}
}
So to simply the issue I want to change my code so the values are reached over 2 seconds and not an instant reset to those values
Any help would be great
Answer by ShadyProductions · Mar 14, 2018 at 04:39 PM
You should use Vector3.Lerp to achieve this affect. https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
I tried using Lerp like this
orbit.xRotation = $$anonymous$$athf.Lerp(orbit.xRot_Stored, -15, 2);
But the correction was still instant no gradual shift
Any ideas ??
Thats not how Lerp works, take a look at the docslink the value still needs to be increased over time, hence the
t += 0.5f * Time.deltaTime;
In that case it means that you'll want to use invoke (ps; you can use return to stop)
void Update()
{
if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.$$anonymous$$ouse2))
Invoke("OrbitTarget", 2);
}
Answer by Harinezumi · Mar 14, 2018 at 05:01 PM
You are looking for interpolation. There are different versions of it, the most common being linear interpolation. For single values (i.e. float
) you can use Mathf.Lerp(), for vectors Vector3.Lerp(), for rotations Quaternion.Lerp() or Quaternion.Slerp() (this corrects for spherical rotation).
Usage example:
private IEnumerator TransitionCoroutine (Vector3 startPosition, Vector3 endPosition, float duration) {
float t = 0;
while (t < duration) {
t += Time.deltaTime;
transform.position = Vector3(startPosition, endPosition, t / duration);
yield return null;
}
transform.position = endPosition;
}
Additionally, check out Unity Wiki's Mathfx class that introduces Hermite()
, Sinerp()
, Coserp()
, and Berp()
for gentler interpolations (they work the exact same way).
I tried using Lerp like this
orbit.xRotation = $$anonymous$$athf.Lerp(orbit.xRot_Stored, -15, 2);
But the correction was still instant no gradual shift
Any ideas ??
Answer by RawallonCG · Mar 27, 2018 at 01:32 PM
If you want to adjust a value over time the logical answer is Lerp. But you don't seem to understand how it works properly (I don't blame you, took me a while to figure out how to use it properly too hehe). In your case since you only want to rotate I'd recommend you to use the RotateTowards, and if you want to delay an action you'll want to use the WaitForSeconds.
Answer by Honorsoft · Mar 14, 2018 at 11:58 PM
Lerp is a good way to 'blend' between two values, but you would have to keep calculating and updating the lerped value. You could put it in the Update() function so the changes made to rotation/position are updated constantly while they are being changed (each frame).
But, what you want to accomplish could get complicated depending on what method you use. First of all, in case anyone still wanted to know about Time.time (in an Update function), here's an easier to understand example:
using UnityEngine;
using System.Collections;
public class TimerExample : MonoBehaviour
{
public float TimeAmount1 = 3; //Delay amount in 'seconds' (frames per second related)
private float myTimer; //The actual timer
void Start ()
{
myTimer = Time.time + TimeAmount1; //Set the timer
}
void Update ()
{
if (Time.time >= myTimer){//Timer went off...Add your code here}
}
}
I mention Time.time here, but just for reference, I don't think you really need it in your case. In Update() you would be instead be calculating the new Lerp value between where the camera is currently and where it's supposed to go, then move the camera to it's new Lerped position, and so on... I was thinking that it might be easier to have something like this:
(C# PSEUDO CODE) bool resetCam = false;
//and during the Update function: if (resetCam = true) {Since the camera is resetting, If the rotation of the camera isn't at the desired rotation then rotate it some more towards it's desired rotation. And if the camera is at it's desired position/rotation then set resetCam to false.}
if (resetCam = false) {Then just do your regular Player rotation stuff, and whenever you need the camera reset, just set resetCam to true.}
If I had to do what you mentioned, I'd probably set up an empty parent object, call it CamParent or something, and then attach the camera as a child. That way, I could attach a rotation-script to the CamParent, and rotate the camera by rotating CamParent.
Anyways, in the pictured setup you'd be rotating on the Y axis, so if it was time to reset the camera position, you could check the current CamParent's Y rotation, and if it wasn't at the start of it's rotation yet (let's say the start Y is 0.0f) then change it gradually until it is. This is where it can get complicated, especially if you want a smooth rotation. (I would not specify a time like you did though of 2 seconds, because if the camera is far from it's desired rotation it might need the 2 seconds, but if the camera is already close to it's desired rotation, 2 seconds isn't needed and will just leave the user waiting for it to idle.) Just to show an example of a rotation script (and show some complications), here's a rotation script that uses AngleAxis to rotate:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateObj : MonoBehaviour {
public float RotateSpeed = 30.0f;
public bool resetCam = false;
//public Quaternion targetRotation = Quaternion.AngleAxis(179.0f, Vector3.up); // just put this for reference
void Update() {
if (Input.anyKey) {resetCam = !resetCam;}
if (!resetCam) {
transform.rotation = Quaternion.AngleAxis (RotateSpeed * Time.deltaTime, Vector3.up) * transform.rotation;
}
else {
transform.rotation = Quaternion.AngleAxis (RotateSpeed * -Time.deltaTime, Vector3.up) * transform.rotation;
}
}
}
So attach that script to CamParent and give the Camera an offset from it. This particular lerp method causes the Y rotation to go from 0 to 180, then switches to -179.999 and 'counts down' (-179.9, -178.x, 177.x, etc.) to 0 again, then starts climbing to 180 again from zero, and so on. I added a resetCam boolean switch that just toggles the rotation direction when any key or mouse click is detected. But the 'weird' Y rotation variables are just from the math involved with Angle.Axis. That script will rotate in a circle, but the math can get confusing. I would rather deal with a 0-360 variable, but I'd still have to figure out way to get it to rotate smoothly back to it's starting rotation. You could compare the difference ('distance') between the desired Y rotation and the current Y rotation, and use that value as a multiplier to speed up(or slow down) the rotation depending on how far from it's desired rotation it is. For example, if it is really far, it's rotation has a higher rotation speed (because it's using the difference as a speed-multiplier), but the closer it gets to it's desired rotation the slower it gets because the multiplier(distance) is decreasing too. Unity has a math function for the distance, not 'Length', but I can't remember the name of it right now. But lerping could also be used to comparatively adjust the rotation also.
To repeat though: I would not specify a time like you did though of 2 seconds, because if the camera is far from it's desired rotation it might need the 2 seconds, but if the camera is already close to it's desired rotation, 2 seconds isn't needed and will just leave the user waiting for it to idle.
In case I gave too much information, basically, since you want a smooth rotation back to 'start', you want to use IF statements to check the rotation. Let's say we had a 0 to 360 degree Y rotation, and it's current Y rotation when the RESET was triggered was 18. You wouldn't want to rotate 'up' to 360 again, you would rotate to 0. Also, if the current rotation was 289 then you would want to rotate 'up' to 360 (not down to zero). Additionally, if you wanted a rotation that sped up automatically if it was far from it's target, you would use the 'difference' of the rotations (or a percentage of it) as a speed-adjuster. I used the same method in making AI space ships that would speed up to catch you, or slow down when close. For you I guess it would be nice if you could just do this: if (transform.rotation.y < orbit.yRotation) {transform.rotation.y +=1;} But it's a little more complicated.
The math function relating to distance, not 'Length', that I couldn't remember was "magnitude", but I don't think it applies here.
Harinezumi mentioned Slerp, I think he's on to something. I haven't got to look it over or use it yet but it seems Quaternion.Slerp is what you need, combined with an IF statement or two in the Update function to see how much rotation you have to do to get to the starting position.
Here's Unity's example for Quaternion.Slerp, it's a great start:
using UnityEngine;
using System.Collections;
public class ExampleClass : $$anonymous$$onoBehaviour {
public Transform from;
public Transform to;
public float speed = 0.1F;
void Update() {
transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, Time.time * speed);
}
}
It does what you need already, it's a constant rotation, not all of a sudden. It's a s$$anonymous$$dy rotation, not a dynamic rotation that adjusts speed according to how far it is from target rotation.
PS, Just to think outside the box, you could also attach the camera to a Nav$$anonymous$$esh and use waypoints to move the camera. Or use the animator system to trigger a rotation of the camera with an Animator.SetBool.
Your answer
Follow this Question
Related Questions
How to have your player controls change while your camera rotates? 0 Answers
How to make camera follow player from point to point 2 Answers
C# > Camera tagged MainCamera > GetComponent<[ScriptClassHere]>() returns null ? 0 Answers
How do I make the character rotate with the 2D camera? 0 Answers
Camera flickers while chasing the player 0 Answers