ZM1KEPKTHS7
ZM1KEPKTHS7

Reputation: 13

How do i get the game object to follow another game object but not move into the targeted object?

how do i get the game object to follow another game object where it will be dragged in the scene but not move into the targeted object? The game object that i want to follow the targeted game object needs to be on top of the targeted game object.

Heres my current code.

public float speed;
public GameObject targetObject;
public Transform myGameObject;


void Update()
{
    myGameObject.transform.position = 
    Vector3.MoveTowards(myGameObject.transform.position,  
    targetObject.transform.position, Time.deltaTime * speed);
}

Upvotes: 0

Views: 74

Answers (1)

Douglas Dwyer
Douglas Dwyer

Reputation: 612

You can check the position of targetObject and get the distance between the two. So, you would check if myGameObject is within a certain radius of targetObject, and if it is not move it towards the position of targetObject.

Your code might look something like this:

void Update()
{
    if(Vector3.Distance(myGameObject.transform.position, targetObject.transform.position) >= minimumDistance) {
        myGameObject.transform.position = 
            Vector3.MoveTowards(myGameObject.transform.position,  
            targetObject.transform.position, Time.deltaTime * speed);
    }
}

Where minimumDistance is the radius in which you don't want myGameObject to move anymore.


Also, you might want to move it to the position above targetObject instead of towards the middle of it. This way, you would do something like this:

void Update()
{
    myGameObject.transform.position = 
        Vector3.MoveTowards(myGameObject.transform.position,  
        targetObject.transform.position + new Vector3(0, up, 0), Time.deltaTime * speed);
}

Where up is how far above the center of targetObject you need the object to be.

Hope this helped!

Upvotes: 1

Related Questions