Have an object move towards another object until it hits a certain spot.

I want the “villager” to move to a tree, or a rock once a certain button is pressed. How I have the code now, it works, he will move to the object, but only while the button is being pressed. - I have to hold T down for him to move.

I want it to be so when I press T (or a UI button in the future), the villager will move to the object and then stop once it hits the object location (or hits just outside of it.) - Does that make sense? lol

What do I need to add in for this to happen? - Thanks! :slight_smile:

[Header("Resource Objects")]
public GameObject _tree;
public GameObject _rock;

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    
    if (Input.GetKey(KeyCode.T))
    {
        CalculateMovement(_tree);
    }

    if (Input.GetKey(KeyCode.R))
    {
        CalculateMovement(_rock);
    }
    
}


void CalculateMovement(GameObject _object)
{
    transform.position = Vector3.MoveTowards(transform.position, _object.transform.position, movementSpeed * Time.deltaTime);
}

}

Hi Reliquiin,

You need to rework your logic. there are many ways to, so here is one, in pseudo code:

Create a boolean variable outside of any function, up with tree and rock
private bool hasTarget = false;
private Vector3 targetLoc;
private float hitThreshold = 1; // how close to the target do you want to get?

   Then, replace the code in your if statements, for example:
void Update() {      
    if( keycode you want to test ){
          hasTarget = true;
          targetLoc =  _tree.transform.position;
     }

then call CallCalculateMovement in the Update loop, without any parameters (remove the param in the declaration

    if( hasTarget )  CalculateMovement();
} /// end of update

Rewrite movement
void CalculateMovement() {
     if( (targetLoc - transform.positon).magnitude > hitThreshold ){
           transform.position = Vector3.MoveTowards(transform.position, targetLoc, movementSpeed * Time.deltaTime);
     }else hasTarget = false
}

This will allow you to switch targets at any time. If you want to prevent that - to force the player to reach the target before trying to move to a new one, wrap all of if GetKey statements inside of one if( ! hasTarget )