Instantiate gameobject between 2 objects in unity

2019-08-14 18:01发布

I have 2 objects. It will be in various direction and distance.

How can i instantiate objects between them with a specific distance.enter image description here

标签: unity3d
2条回答
爷、活的狠高调
2楼-- · 2019-08-14 18:28

My suggestion would be to calculate the vector between the two objects, like this

Vector3 objectLine = (object2.transform.position - object1.transform.position);

Store the magnitude of that vector

float distance = objectLine.magnitude;

Then, normalise the vector;

objectLine = objectLine.normalized;

Iterate through the line, instanciating the object you want to create a specific distances

Vector3 creationPoint = object1.transform.position;
float creationPointDistance = (object1.transform.position - 
    object1.transform.position);
while(creationPointDistance < distance)
{
    creationPoint += objectLine * NEW_OBJECT_DISTANCE;
    creationPointDistance = (object1.transform.position - 
        object1.transform.position);
    if(creationPointDistance < distance)
    {
        objects.Add((GameObject)Instanciate(newObject, creationPoint, 
            new Vector3(0.0f,0.0f,0.0f)));
    }
}

What that will do is set the initial point to be object1's position. It will then move a set distance along the vector between object 1 and object 2, check it's within the two objects, and if it is, instanciate the object, storing it in a list of gameobjects.

That hopefully should do it. I don't have Unity (or any IDE) in front of me to check the syntax.

查看更多
干净又极端
3楼-- · 2019-08-14 18:29
var centerLocation : Vector3 = Vector3.Lerp(object2.transform.position - object1.transform.position, 0.5);

Vector3.Lerp will determine the Vector3 location between 2 Vector3s at a specified percentage. 0.5 = 50%.

查看更多
登录 后发表回答