- Home /
Spawning object 1 unit in front of current rotation
I need to spawn an object in a specific direction. I need to spawn the object 1 meter/unity unit in the current camera's rotation. How do I do this?
Instantiate (newGameObject, /* a new position */, Quaternion.EulerAngles(0, 0, 0))
Basically, wherever the camera is looking, I need to spawn an object 1 meter in front of it. It the camera is looking up, I want to spawn the object 1 meter above the camera and when the camera is looking down, I want to spawn it 1 meter below it.
Answer by Baste · Dec 08, 2014 at 02:40 PM
Transform camT = Camera.main.transform;
Instantiate (newGameObject, camT.position + camT.forward, Quaternion.identity)
The forward variable of a transform gives a one unit long direction vector facing directly forward from the transform. If you add it to the transform's position, you get a position one in front of the transform. If the script you're using is on the camera, just refer to the transform directly instead of going through Camera.main.
Oh, and I replaced Quaternion.EulerAngles(0, 0, 0) with Quaternion.identity. They're the same thing, but without the transformation from Vector to Quaternion.
Answer by piece-of-toast · Dec 09, 2014 at 06:01 AM
public GameObject newGameObject;
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp ("e"))
{
Instantiate (newGameObject, transform.position + this.transform.forward, transform.rotation);
}
}
That will instantiate an object in front of what ever object the script is attached too. Unless you mess around with vectors a lot transform.forward should always be in front of you.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to make Camera position Independent of its Rotation? 1 Answer
Unfreezing rotation causes the position and rotation go crazy 0 Answers
Unity Rotation Not Working Properly? 1 Answer
Set controller to active script - how do I transform him to the correct position? 1 Answer