- Home /
Instantiateon custom rotation doesn't work
Hello,
I made this script to instantiate a projectile on a gameobject A. The script is attached to another gameobject, and object A is a child of the main camera, meaning that it rotates with the camera.
The problem is that the gameobject A has the same rotation on the inspector as it is a child object, and the result is that the projectile gets instantiated with the same rotation every time. How can I fix it?
var rot = Quaternion.Euler(A.transform.rotation.x, A.transform.rotation.y, A.transform.rotation.z);
Instantiate(projectile, A.transform.position, rot);
Answer by robertbu · Aug 24, 2013 at 03:18 PM
'transform.rotation' is a Quaternion...a 4D, non-intuitive construct. The components are not degrees, and you should not use the independent components of a Quaternion unless you understand the math behind them. Unity gives a number of helper functions, so you should not have to use the independent components.
For what you are doing here, you could just:
var rot = A.transform.rotation;
Or even eliminate 'rot':
Instantiate(projectile, A.transform.position, A.transform.rotation);
The problem is that I add a float to the y axis of the rotation, as an offset. The rotation of the sphere doesn't change as it's a child object
You can combine rotations:
Instantiate(projectile, A.transform.position, Quaternion.AngleAxis(25.0, Vector3.up) * A.transform.rotation);
Answer by perchik · Aug 26, 2013 at 02:43 PM
What @robertbu said is completely correct [as always].
As an alternative, you can use transform.rotation.eulerAngles.x
in the same way you are currently doing. This would access the actual euler angles of your rotation, instead of the more abstract quaternion:
var rot = Quaternion.Euler(A.transform.rotation.eulerAngles.x, A.transform.rotation.eulerAngles.y, A.transform.rotation.eulerAngles.z);
Instantiate(projectile, A.transform.position, rot);