简体   繁体   English

我如何使游戏对象跟随另一个游戏对象但不移动到目标对象中?

[英]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);
}

You can check the position of targetObject and get the distance between the two. 您可以检查targetObject的位置并获取两者之间的distance 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 . 因此,您将检查myGameObject是否在targetObject的特定半径内,以及是否没有将其移向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. 其中minimumDistance是您不希望myGameObject再移动的半径。


Also, you might want to move it to the position above targetObject instead of towards the middle of it. 另外,您可能希望将其移动到targetObject上方的位置,而不是向中间移动。 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. up是您需要将对象置于targetObject中心上方多远的位置。

Hope this helped! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM