dangoqut132
dangoqut132

Reputation: 47

How to rotate child objects around their own pivot points Unity3D?

I debugged my issue and found that all child objects of my camera are rotating in place based on the position of the camera. the offset seems to be part of it, but i need that to make the camera follow my rigged players head. i can’t seem to separate this so that i can make my child objects rotate around their own individual pivot points. The gun which is a child object of the camera arcs up and down way beyond its default position near the chest area which is not good.

My setup is first person, it’s just Main Camera (position (0,1.7,0)) as the root object and then my placeholder Gun object (position (0,0,0)) as a child of it. My Player is separate from the camera and contains the MouseLook/Camera script.

I tried adding a empty object inbetween the camera and gun but that did not solve anything either. I even unparented the gun, made it follow the camera via script and it still occured.

public class MouseLook : MonoBehaviour
{
    public Transform playerHead;
    public Vector3 offset = new Vector3(0f, 0.12f, 0f);

    private Transform playerCam;
    private Quaternion targetRotation;

    public float rotX = 0f;
    public float rotY = 0f;

    public float mouseX;
    public float mouseY;

    public float mouseSensX = 2f; 
    public float mouseSensY = 2f; 

    void Start()
    {
        playerCam = Camera.main.transform;
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        mouseX = Input.GetAxisRaw("Mouse X") * mouseSensX;
        mouseY = Input.GetAxisRaw("Mouse Y") * mouseSensY;

        rotY += mouseX;
        rotX -= mouseY;
        rotX = Mathf.Clamp(rotX, -90f, 90f);

        playerCam.position = playerHead.position + offset;

        targetRotation = Quaternion.AngleAxis(rotY, Vector3.up);
        transform.rotation = targetRotation;

        playerCam.rotation = Quaternion.Euler(rotX, rotY, 0f);
    }
}

Upvotes: 0

Views: 31

Answers (0)

Related Questions