Hello,
I have a 3d space, with a camera that can have different angles to view at a plane.
Now I want to be able to drag and drop a game object on the X- and Z-axis on the plane, with the y-axis (height) being locked, so that it looks like I move a chess piece on a board.
Currently my game object starts to fly, but when locking the Y-axis the mouse is faster than the game object.
What I want is what you can see in this example:
I have searched this forum and stack overflow but I could not find a working example or an Idea how to make that happen.
This post describes my problem, that my mouse is not staying on the object when moving my mouse on the y-axis(screen space), it moves faster than my object on the Z-axis (in world space)
https://gamedev.stackexchange.com/questions/134213/mouse-position-to-world-position-help
When the camera looks 90degree downwards on the plane, the translation is correct, so I assume I need to take the angle in account to calculate the correct z value in world space to align with my mouse position? Or a way to know the Z position where I want my object to drag to, but also not sure how to retrieve that.
Is there any Idea how I could accomplish this?
This is the current code I use with the Y-axis being locked to the dragging object
private GameObject _drag;
private Vector3 screenPosition;
private Vector3 offset;
private void Update()
{
if (_drag == null && Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
if (gameObject == hit.transform.gameObject)
{
_drag = hit.transform.gameObject;
screenPosition = Camera.main.WorldToScreenPoint(_drag.transform.position);
offset = _drag.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
}
if (Input.GetMouseButtonUp(0))
{
_drag = null;
}
if (_drag != null)
{
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
_drag.transform.position = new Vector3(currentPosition.x, _drag.transform.position.y, currentPosition.z);
}
}