- Home /
world direction to local when instantiating
Hi! I am trying to get some 3d menu going. I have found a script that does what i want - instantiate object around center in circle:
if(Input.GetKeyUp(KeyCode.LeftAlt))
{
var center = my3dCamera.transform.position;
for (i = 0; i < 5; i++)
{
var pos = RandomCircle(center, 2);
// make the object face the center
//var rot = Quaternion.FromToRotation(Vector3.forward, center-pos); //not needed
var clone = Instantiate(button, pos, transform.rotation); //rot
}
}
function RandomCircle(center:Vector3, radius:float): Vector3 {
// create random angle between 0 to 360 degrees
var ang = Random.value * 360;
var pos: Vector3;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.y = center.y + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.z = center.z;
return (pos);
}
i have attached this script to main camera. Problem is that i cant get my camera local direction. center variable is always pointing in the world rotation(or direction). How can i pass "center" to RandomCircle function in it's (camera this script is attachet to) local direction?
I have tried transform.localRotation, transform.TransformDirection, InverseTransformDirection, but nothing works. They are instantiated off screen, but always facing world coords.
Answer by syclamoth · Jan 22, 2012 at 06:44 AM
Try this-
var pos = my3dCamera.transform.TransformPoint(RandomCircle(center, 2));
And then after you've instantiated the cube to rotate it so it faces the camera, use
clone.transform.LookAt(my3dCamera.transform);
This way, your circle will align with the camera's local axes, and the cubes will face the camera.
I tried to test this with simpler code:
var center : Vector3 = my3dCamera.transform.position;
center.z = transform.position.z + 5;
var clone = Instantiate(button, center, transform.rotation);
clone.transform.parent = transform;
Cude is facing ok, but is instantiated in global pos of myCamera. So position, or rotation of instantiated cubes must be set before instantiate. After adding:
clone.transform.localPosition = center;
the cube is instantiated off screen.
Oh, I just realised something. The 'center' variable is a trap- you should just be using Vector3.zero for that! Just calculate the offsets, and use TransformPoint to make the offsets relative to the camera, in local coordinates.
wait, so center should be (0,0,0)? If so, then cubes will be made in world center, and... ...
OH GOD! IT WOR$$anonymous$$S!!
Thank you!! And +1 internetz for you because star wars reference :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613063247im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
bone rotations changed in 4.3.2 inspector? 0 Answers
Local to World space 0 Answers
Transform.Rotate for Quaternions? 1 Answer
Objects local/world cordinate question 1 Answer
Transform.right misunderstanding 2 Answers