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.
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.
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.