I want to move my object along the X-Z plane only and restrit the Y-axis. Here is my code:
Vector3 mousePosition;
private Vector3 GetMousePos()
{
return Camera.main.WorldToScreenPoint(transform.position);
}
private void OnMouseDown()
{
mousePosition = Input.mousePosition - GetMousePos();
}
private void OnMouseDrag()
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - mousePosition);
}
Any ideas how I can restrict it?
Hi Matthewman96. One way would be like the below:
Vector3 mousPosition = GetMousePos();
mouseposition.x = 0;
mouseposition.z = 0;`
Then, the mousPosition
value will be (0, REAL_VALUE, 0)
I hope it helps.
Or maybe like below:
private Vector3 GetMousePos()
{
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos.x = 0;
pos.z = 0;
return pos;
}
Hi,
You can use Math:
First, you already have Two Point: the camera pos, and a point caculate by Camera.main.ScreenToWorldPoint
and Input.mousePosition
and a z-depth but 0.
Then you can get the line equation of these two point.
Finally, you can use a particular Y values to get the point you want from the line equation.
Or,
if you have a plane with a Y-value you want to restrict. Then you can use Camera.man.ScreenPointToRay()
to get the collision pos. That pos will be your wanted.