Im sure this is fairly simple but I can’t seem to work it out.
I have an object which is attached to a parent. I have the object locked on the X and Z axis so that it can only be dragged in the y axis. As I move the mouse up and down I want the child object to do so but only in the Y-Axis. this works find as long as the rotation of the camera is at 0,0,0 but the moment I move the camera so it is say side on to the object (0,90,0) or any other rotation that isnt 0,0,0 up becomes down and down becomes up. Can anyone explain to me why this happens and how I can make it consistent? My code is below…
You haven’t given enough information here for a definitive answer to your problem. You have camera rotation, camera position, and a parent/child relationship that may play a part in this problem. One critical issue is your calculation of the ‘z’ in your ‘mousePos’. That distance needs to be the distance from the camera plane to a plane passing through the object that is parallel to the camera plane. So your calculation above will work as long as the camera is axes aligned and point towards positive ‘z’. Given that your object is “locked on the X and Z,” you might get away with an alternate calculation:
Note this will yield an approximation. A ‘right’ solution for finding a world position with an arbitrary camera rotation is to use Unity’s mathematical Plane class. You can construct a plane at your object using the camera’s forward as a the normal. Then you can use Plane.Raycast() to find the position in 3D space.
Note if you don’t care how well the real object tracks the mouse movement, you can just use a conversion factor and convert the delta ‘y’ moves of the mouse to the ‘y’ movement of your object.