Hello Guys! I tried to create a script that moves the character to the closest point (tagged LeapPoint) when the F key is pressed. But character doesnt smoothly travel the whole distance to the point when pressed, only moves instantly to certain distances when pressed.
So instead of smoothly moving towards the point over time when F is pressed, it suddenly jerks towards the point a fraction of the way.
I know that MoveTowards needs to be in the update function but then I wouldnt know how to play it when F is pressed. Can someone help me!!!
public GameObject myChar;
public float speed = 1f;
public Transform target;
void Start () {
myChar = this.gameObject;
}
void Update ()
{
FindClosestPoint ();
if (Input.GetKeyDown (KeyCode.F))
{
MoveToPoint()
}
}
void MoveToPoint(){
float step = speed * Time.deltaTime;
myChar.transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
public GameObject FindClosestPoint()
{
GameObject[] points;
points = GameObject.FindGameObjectsWithTag("LeapPoint");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject point in points) {
Vector3 diff = point.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance && point.GetComponent<LeapPoint>().hasLeaped == false) {
closest = point;
distance = curDistance;
target = closest.transform;
}
}
return closest;
}
}