I basically have a camera and want it to follow a moving point such that the camera’s speed changes accordingly with the distance between it and the target point non-linearly
I have written this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetFollow: MonoBehaviour {
public GameObject FollowThis;
public float speed = 2f;
float step;
// Update is called once per frame
void Update (){
step = speed * Time.deltaTime;
this.gameObject.transform.position = Vector3.MoveTowards (this.gameObject.transform.position, FollowThis.gameObject.transform.position, step);
}
}
Now the problem I am getting is that the moving speed of the camera is very slow and that of my target point is high. When my target goes out of range of the camera (very far away), the camera takes too long to return to the target. Also when the camera returns at the target point, it overshoots. There is also a lot of jittering. Any idea how to correct this?
Try using SmoothDamp and see if it works better:
1 Like
Thanks! Now it is following correctly a little bit. But sometimes, the camera overshoots and takes some time to return to the point even I set the value of SmoothTime as low as 0.5f. What I want is that camera should increase its speed towards target if distance increases and decrease speed if distance decreases.
I changed the code to this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetFollow : MonoBehaviour {
/* gradiently increase step accorign to distacee */
public GameObject FollowThis;
public float speed = 2f;
float step;
Vector3 vel = Vector3.one;
// Update is called once per frame
void Update (){
/*step = speed * Time.deltaTime;
this.gameObject.transform.position = Vector3.MoveTowards (this.gameObject.transform.position, FollowThis.gameObject.transform.position, step);
*/
this.gameObject.transform.position=Vector3.SmoothDamp (this.gameObject.transform.position, FollowThis.gameObject.transform.position, ref vel, 0.5f);
}
}
Also, what is the use of "ref velocity "
“ref velocity” means that the variable you’re sending in is by reference, instead of by value. Normally a Vector3 (struct) would be copied to a method call (ie: not the original). By using the ‘ref’ keyword, this function will read & modify the original value … which will be updated after it’s returned.
There is a max speed setting, one of the overloads for SmoothDamp, I believe. You might want to set (/change) the max velocity value based on distance and pass that into the other overload of the method.