How do I move a GameObject on local z axis with a moving camera?
I'm trying to make a puzzle game where you can move the camera around by dragging the outside of the world. Right now I'm trying to make a draggable object in the game that only drags across the x axis but the issue I'm having is it only works on one perspective. So from the front it works because "x" is either positive or negative and from the back, you have to flip it so it doesn't go the opposite direction. But when you start dragging from a 45 degree angle its awkward and doesn't work. Is this the right approach to the problem? Thanks in advance!
float x = Input.GetAxis("Mouse X");
transform.localPosition = new Vector3(transform.position.x + x * movingSpeed, transform.position.y ,transform.position.z);
Answer by skiddswarmik · Jun 05, 2020 at 03:36 PM
I figured it out, so the problem was the idea of using Input.GetAxis("Mouse X"); because that's relative to where I am in the world. It works from single perspective games but when you start panning the camera around the subject it no longer works. So I read some other documentations and forums and figured it out.
private Vector3 mouseOffset;
private float mouseZ;
void OnMouseDown()
{
mouseZ = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
// Get Offset
mouseOffset = gameObject.transform.position - GetMousePoint();
}
private Vector3 GetMousePoint()
{
// Get Mouse Co ordinates
Vector3 mousePoint = Input.mousePosition;
//set Z to gameobject z
mousePoint.z = mouseZ;
// Convert it to world points
return Camera.main.ScreenToWorldPoint(mousePoint);
}
void OnMouseDrag()
{
Vector3 newPosition = GetMousePoint() + mouseOffset;
transform.position = new Vector3(transform.position.x, transform.position.y, newPosition.z);
}
Basically I'm turn mouse coordinates into in game position using GetMousePoint() and creating an offset so the object doesn't snap in the middle immediately, and changing only the z position when dragging the mouse in the z direction.
Your answer
![](https://koobas.hobune.stream/wayback/20220613000154im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to control an object after clicking on it? 1 Answer
Need help with Descending Orbit Game Object (Plane Crashing) 0 Answers
Making GameObject move in the direction of my mouse (3d) 0 Answers
Mouse Position Jumps when Leaving Game Window 0 Answers
How to Setactive(true) the other class ? 0 Answers