Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to get a spawned object to face the side of the camera

Discussion in 'Scripting' started by OutDoorsScene, Jan 18, 2023.

  1. OutDoorsScene

    OutDoorsScene

    Joined:
    Sep 9, 2022
    Posts:
    140
    ezgif-5-1858f8aa5d.gif
    I want the spawned gameobject to face the side of the camera point of view.
    Code (CSharp):
    1. Vector3 DropPosition = Playercamera.transform.position + Playercamera.transform.forward;
    2. Quaternion Droprotation = Playercamera.transform.localRotation;
    3.  
    4. DroppedItem = Instantiate(ItemsToDrop.AutomaticSidearm, DropPosition, Droprotation);
    5.  
    6. DroppedItem.transform.rotation = Quaternion.Euler(0,90,0);
    7.  
    8.  
    9.  
    The camera is a child, and the y axis uses a modulo operator, it also uses
    Quaternion.Euler()
    to rotate. I'm not sure if this has a effect of the spawned item.

    Code (CSharp):
    1. if (CursorLock == true)
    2.         {
    3.          Cursorfloat = 1;
    4.         }
    5.         else
    6.         {
    7.             Cursorfloat = 0;
    8.         }
    9.  
    10.         float MouseX = Input.GetAxisRaw("Mouse X") * Sens * Time.deltaTime * Cursorfloat;
    11.         float MouseY = Input.GetAxisRaw("Mouse Y") * Sens * Time.deltaTime * Cursorfloat;
    12.  
    13.         XRotation -= MouseY;
    14.         YRotation += MouseX;
    15.  
    16.         // This line keeps the YRotation within -360 360.
    17.         YRotation = (YRotation + MouseX) % 360;
    18.  
    19.         XRotation = Mathf.Clamp(XRotation, -90, 90);
    20.         transform.rotation = Quaternion.Euler(XRotation,YRotation,0);
     
    Last edited: Jan 18, 2023
  2. davidnibi

    davidnibi

    Joined:
    Dec 19, 2012
    Posts:
    424
    Have an existing camera-child object with your desired transforms, and copy those to the new object, that's what I do. ;)

    You should use localRotation for all child objects if you haven't already.
     
    OutDoorsScene likes this.