Home > Blockchain >  How can I rotate an Object around the camera (angle)?
How can I rotate an Object around the camera (angle)?

Time:07-28

What I want to do is spawn an object in front of the camera and the side I am looking at. When I change the rotation of the camera (looking at a different side), the object is still spawned at the same position. How can I change this (that the Object also changes his angle)?

public void Create(Object myPrefab)
{
    Vector3 instantGO = Camera.main.transform.position   new Vector3(0, 0, 7);
    Instantiate(myPrefab, instantGO, Quaternion.identity);
}

CodePudding user response:

Use transform.forward - this gives a position relative to the transform e.g. Camera.main.transform.position (Camera.main.transform.forward * 5) for 5m in front of the cam.

The forward and left properties return a vector of magnitude one, pointing in the direction the transform is facing, or to it's left. You can use -forward and -left to align backwards or to the right. Add this to the position of the object and multiply it to give a position a number of units away. In recent versions of Unity you also have transform... up, down, right etc.

CodePudding user response:

Use this Instantiate variant:

Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent); 

And pass the Camera transform as the parent parameter. This will make the new object a child of the camera and thus always moves/rotates with the camera.

  • Related