- Home /
Instantiate between 2 game objects.
Hi,
I am trying to instantiate cube prefab between 2 objects.I am drawing lines with vectorsity and when i completed shape my script trying to instantiate object between 2 points.
My lines using vector3 and also i am working on X / Y axis. when i instantiate prefab between 2 points i have to rotate them in Z axis. But when i tried to instantiate an object there is no rotations applied.
That black line is my cube on isometric cam view and i want to rotate them between 2 vector3 points. I need some advices for calculating rotation on z axis.
How can i do that ?
Sorry for my bad english
Best Regards and Thanks
Answer by rutter · Nov 13, 2013 at 01:30 AM
The simple version of Instantiate() takes only one argument: the object to copy.
There's a three-argument form that takes the object to copy, then the target position and rotation for that object.
Something like this:
var fooClone = Instantiate(foo, Vector3.zero, Quaternion.identity);
Now, let's suppose you have two points, v1
and v2
. You'd like to spawn an object between them.
//random point between v1 and v2
//you already have this, but someone else might read this thread...
Vector3 pos = Vector3.Lerp(v1, v2, Random.value);
//vector pointing from v1 to v2
Vector3 separation = v2 - v1;
//rotation facing from v1 to v2
Quaternion rot = Quaterion.LookRotation(separation);
//spawn
GameObject copy = (GameObject)Instantiate(someOtherGameObject, pos, rot);
Handy reading:
http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.LookRotation.html
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html
http://docs.unity3d.com/Documentation/ScriptReference/Random.html
Google "vector subtraction" if the separation formula seems unusual
Answer by robertbu · Nov 13, 2013 at 01:27 AM
For the object you are putting in the middle, you have to pick a side you are going to have face along the line. So given you are saying the rotation along the 'z', I'm going to assume you want the right side of the object to face the second square. Given the Vector3 positions of the two squares as 'pos1' and 'pos2', you can align the right side as:
var v3 = pos2 - pos1;
transform.rotation = Quaternion.FromToRotation(transform.right, v3) * transform.rotation;
Another solution is to fist construct your object you are placing so that the side facing positive 'z' is the one you want to point at block 2 (pos2). Then you can do this:
Transform.LookAt(pos2, Vector3.forward);