Converting local position movement to global position movement?

So I have a problem that probably has an easy fix but I’m currently just not seeing the forest for the trees.

I want do to a slight camera movement to emulate a handheld-look and thus have a script attached to my camera that just moves it on the x and y.

It works well, but when the camera’s rotation doesn’t align with the global axis, the movement is of course off.
My question is, how do I change/adapt my script so it moves the camera on it’s local x/y axis, or how do I calculate this into the target position?
(change the target position so it lines up again?)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFloat : MonoBehaviour
{
 	public float speed;
    public float speedFluctuation;
    public Vector3 floatRange;
    private Vector3 startingPos;
    private Vector3 randomPos;

    void Start()
    {
       startingPos = this.transform.localPosition;
       StartCoroutine(HoverLoop());
    }
    
    IEnumerator HoverLoop()
    {
        while(enabled)
        {
            randomPos.x = startingPos.x + Random.Range(-floatRange.x, floatRange.x);
            randomPos.y = startingPos.y + Random.Range(-floatRange.y, floatRange.y);
            randomPos.z = startingPos.z + Random.Range(floatRange.z, floatRange.z);

            LeanTween.moveLocal(this.gameObject,randomPos,speed).setEase(LeanTweenType.easeInOutSine);
            yield return new WaitForSeconds(speed*Random.Range(1, speedFluctuation));
            LeanTween.moveLocal(this.gameObject,startingPos,speed).setEase(LeanTweenType.easeInOutSine);
            yield return new WaitForSeconds(speed*Random.Range(1, speedFluctuation));
        }
    }
}

Please keep in mind that for an object in the root of the scene, its localPosition and position are the same. This may cause problems when trying to create that handheld effect.

Create a cameraParent object.

Put the camera inside the parent.

Rotate the parent object using the mouse or whatever input device you’re using.

This way the camera’s local position will always be relative to the parent object and the parent object will automatically translate those positions to global positions.

If you do this, I think you’ll have to make this change:

// Old code
startingPos = this.transform.localPosition;

// New code
startingPos = Vector3.zero;

Hey Ady_M,

Thanks for your reply and solution, this totally worked.

My Camera was already a child of an object but moved to a specific location, I made it a child object of a new GameObject so the camera transform could be 0,0,0.
I rotated the parent object, so the camera transform has no rotation on it either.

Then I also updated the code to your suggestion, and now it’s behaving exactly how I want it to.

Thanks again!