- Home /
Move 3d objects in axis according to camera
I have a 3d object(cube) and I want to move it in a single axis according to both mouse-drag (which translates to up/down/left/right) and camera rotation around that cube. (to rotate the camera around the object I followed https://github.com/EmmaPrats/Camera-Rotation-Tutorial).
For example if the camera rotation is (0,0,0) and the swipe direction is up the direction Vector3 I get should be (0, 1, 0). If the camera rotation is (90,0,0) and the swipe direction is up the direction Vector3 I get should be (0, 0, 1).
You can disregard camera rotation in the Z-axis. As I dont rotate the camera around it.
How can I achieve that?
Thanks
Answer by Kona · Nov 12, 2021 at 01:23 PM
There's a handy method of the Tranform class to use for this purpose.
https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html
To get a direction relative to a game object's transform component:
Vector3 inputDir = new Vector3( Input.GetAxis( "MouseX" ), Input.GetAxis( "MouseY" ), 0f ); //Get mouse motion, I think it's called MouseX and MouseY, check the input settings though.
Vector3 camToWorldDir = Camera.main.transform.TransformDirection( inputDir ); //Creates a new vector pointing in the inputDir relative to the main camera's current rotation.
thanks, ill try that. will it work in mobile as well? (seeing as it's name is mouse..)
The first line with the mouse part is the input method. The conversion happens in next lines. Obviously, you can change your input method to whatever you want
Yea I checked about it. I though it was some complicated math or something.. I think it works now :) thanks a lot!