Hi.
I am creating a 3D project and what I want to achieve is to move an object by dragging a mouse along the z-axis from z-position of -12 to -16 where the speed of the object gets reduced to 0 when it reaches a certain point. To make it easier to understand, I am trying to use mouse to pull an object as if I am using a slingshot.
What I have so far is something along these lines:
public class Stone : MonoBehaviour
{
private Vector3 mouseOffset;
private float mouseZ;
private float dragSpeed = 0.1f;
void OnMouseDown()
{
// A linear function for dragSpeed of 0.4 when z-position is -12; and 0 when z-position is -16
dragSpeed = gameObject.transform.position.z * 0.1f + 1.6f;
// Mouse z-position converted from World to Screen point
mouseZ = Camera.main.WorldToScreenPoint(gameObject.transform.position).y*dragSpeed;
// Get Mouse Offset: Difference between Object position and Mouse position in World Point
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()
{
if(Input.GetButton("Fire1"))
{
// Position in World Point
Vector3 newPosition = GetMousePoint() + mouseOffset;
if (newPosition.z > -16 && newPosition.z < -12)
{
transform.position = new Vector3(transform.position.x, transform.position.y, newPosition.z);
}
}
}
}
I am linking the z-position to y-position of the mouse in method OnMouseDown
so that the player could move the object even by dragging the mouse to the side and up/down.
The code is not working well, since the drag speed is set only when the mouse is down and then gets unchanged until I release the mouse. Ideally, the drag speed should be dynamically adjusted in method OnMouseDrag
. However, if I adjust the z-position there, the object immediately moves back on the screen (newPosition.z is multiplied by a drag speed).
Does anyone have a suggestion what is the best way to move an object along the z-axis as described above?
Many thanks!